问题
What's the correct syntax to make this work?
public boolean isTypeOf(Class type) {
return this instanceof type;
}
I intend to call it with:
foo.isTypeOf(MyClass.class);
The method will be overriden, otherwise I would just use instanceof
inplace.
回答1:
Use Class.isInstance(obj):
public boolean isTypeOf(Class type) {
return type.isInstance(this);
}
This method determines if the given parameter is an instance of the class. This method will also work if the object is a sub-class of the class.
Quoting from the Javadoc:
This method is the dynamic equivalent of the Java language
instanceof
operator.
来源:https://stackoverflow.com/questions/32696912/using-instanceof-with-a-class-object