Java中检查对象类型的不同方法? [英] different ways of checking the type of an object in java?
问题描述
我有一个对象 obj 和一个类名 MyClass ,我可以使用instanceof来检查obj是否为MyClass类型,或者我可以说obj.getClass().equals("MyClass").所以我想知道还有其他检查对象类型的方法.
I have an object obj and a class name MyClass, i can check whether obj is of the type MyClass using either instanceof or i can say obj.getClass().equals("MyClass"). So i want to know are there any other ways of checking the type of an object.
推荐答案
当心:如果您的对象是 MyClass
的子类或实现,则 instanceof
也会返回true界面(通常是您感兴趣的界面-如果您想起"IS A" OOP概念)
Beware: instanceof
returns true also if your object is a subclass of MyClass
, or if it implements the interface (this is usually what you are interested in - if you recall the "IS A" OOP concept)
另请参阅此关于Class.isAssignableFrom()
,类似于 instanceof
,但功能更强大.
See also this about Class.isAssignableFrom()
, similar to instanceof
but a little more powerful.
这篇关于Java中检查对象类型的不同方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!