Use instanceof in a generic way

匆匆过客 提交于 2020-01-05 06:59:09

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!