ab11
ab11

Reputation: 20090

How to use type of a class as a parameter?

How would I write and call the method boolean doInstanceof(...) which takes an Object o and a type t and returns true if o is an instance of t, returns false otherwise.

Something like:

boolean doInstanceof(Object o, type t)
{
    return o instanceof t;
}

//called like
boolean isInstance = doInstanceof(new MyClass(), MyClass.type())

Upvotes: 0

Views: 95

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500525

You can use Class and its isInstance method:

boolean doInstanceOf(Object o, Class<?> clazz)
{
    return clazz.isInstance(o);
}

boolean isInstance = doInstanceOf(new MyClass(), MyClass.class)

Mind you, that's only replacing one method call for another - you might as well call Class.isInstance directly:

boolean isInstance = MyClass.class.isInstance(new MyClass());

(I'm assuming that in reality you don't know the class at compile-time, otherwise you should just use instanceof of course.)

Upvotes: 5

Related Questions