membersound
membersound

Reputation: 86727

How to pass a class type as parameter and cast to it?

Why can't I cast an object to a class type that I provide via paramter?

public static checkInstanceOf(Object obj, Class<?> type) {
    return obj instanceof type; //error: type cannot be resolved to a type
}

I'd like to create a utility method that has to use an instanceof check like this in a more detailed routine. What would I have to change?

I'd like to be able to call something like this:

MyUtil.checkInstanceOf(new String(""), MyClass.class);

Upvotes: 2

Views: 1744

Answers (1)

Dawood ibn Kareem
Dawood ibn Kareem

Reputation: 79838

You want to use the isInstance method of the Class class.

Upvotes: 4

Related Questions