问题
Is there a way to use instanceof based on the passed argument of a method? Example
doSomething(myClass.class); /* I would like to call this also with other classes */
public void doSomething(/*generic parameter that accepts all classes, not just myClass */) {
if (myObject instanceOf /* the generic parameter */ == true) {...}
}
sometimes I'll call the method using myClass.class but other times I would like to call it using someOtherClass.class - I don't want to change the if condition though. Is that possible? If so, how? :)
Thanks
回答1:
You're looking for the Class.isInstance() method.
public void doSomething(Class<?> c, Object myObject) {
if (c.isInstance(myObject)) {...}
}
回答2:
This is the way to do it, as far as I know:
public static <T> boolean doInstanceOf(Object object,Class<T> clz) {
return clz.isInstance(object);
}
Usage:
System.out.println(doInstanceOf(myObject,MyClass.class));
来源:https://stackoverflow.com/questions/13768049/use-instanceof-in-a-generic-way