Java instanceof运算符 [英] Java instanceof operator

查看:126
本文介绍了Java instanceof运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一个有效的类Type变量可以与 instanceof 运算符一起使用?例如:

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
}

作为替代方案:

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

是否有任何性能优势?

推荐答案

你所做的事情实际上并不相同。考虑一下子类会发生什么(我知道你不能继承 String ,所以在 String 的情况下,它不会问题)。

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

如果你有一个对象而你想知道它是否是某个类型的实例并且你有 Class 对象,你可以使用 Class#isInstance method。

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.

这篇关于Java instanceof运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆