Java instanceof operator

偶尔善良 提交于 2019-12-17 16:52:58

问题


Is there a valid class Type variable that can be used with the instanceof operator? For Example:

String s = "abc";

Class<?> classType = String.class;

if (s instanceof classType) {
    //do something
}

as an alternative to this:

if (s.getClass() == classType) {
    //do something
}

Would there be any performance benefit?


回答1:


What you're doing is not actually the same. Consider what happens with subclasses (I know you can't subclass String, so in the String case it doesn't matter).

class A {}
class B extends A {}

B b = new B();
b instanceof A // true
b.getClass() == A.class // false

If you have an object and you want to know if it is an instanceof a certain type and you have the Class object, you can use the Class#isInstance method.

In either case, I expect performance differences to be insignificant.




回答2:


There's also

Class<?> classType = String.class;

if (classType.isInstance(s)) {...

As for performance, I'd expect the differences between any of these to be negligible.



来源:https://stackoverflow.com/questions/11751550/java-instanceof-operator

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