何时使用Class.isInstance()&什么时候使用instanceof运算符? [英] When to use Class.isInstance() & when to use instanceof operator?

查看:48
本文介绍了何时使用Class.isInstance()&什么时候使用instanceof运算符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
Java isInstance与instanceOf运算符

何时使用 Class.isInstance()以及何时使用 instanceof 运算符?

When to use Class.isInstance() and when to use instanceof operator?

Java提供了两个选项来检查分配兼容性.什么时候使用?

Java is providing two option for checking assignment compatibility. Which to use when?

推荐答案

我认为官方

I think the official documentation gives you the answer to this one (albeit in a fairly nonspecific way):

此方法是Java语言instanceof的动态等效项运算符.

This method is the dynamic equivalent of the Java language instanceof operator.

我认为这意味着 isInstance()主要用于在运行时处理类型反射的代码.特别是,我想说它的存在是为了处理您可能事先不知道要检查其成员资格的类的类型的情况(尽管这些情况可能很少).

I take that to mean that isInstance() is primarily intended for use in code dealing with type reflection at runtime. In particular, I would say that it exists to handle cases where you might not know in advance the type(s) of class(es) that you want to check for membership of in advance (rare though those cases probably are).

例如,您可以使用它编写一种方法来检查两个任意类型的对象是否与赋值兼容,例如:

For instance, you can use it to write a method that checks to see if two arbitrarily typed objects are assignment-compatible, like:

public boolean areObjectsAssignable(Object left, Object right) {
    return left.getClass().isInstance(right);
} 

通常,我想说,每当您知道要预先检查的类的种类时,应该首选使用 instanceof .在极少数情况下,您不需要使用 isInstance().

In general, I'd say that using instanceof should be preferred whenever you know the kind of class you want to check against in advance. In those very rare cases where you do not, use isInstance() instead.

这篇关于何时使用Class.isInstance()&什么时候使用instanceof运算符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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