Reputation: 20090
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
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