简体   繁体   English

Java中检查对象类型的不同方法?

[英]different ways of checking the type of an object in java?

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"). 我有一个对象obj和一个类名MyClass ,我可以使用instanceof检查obj是否为MyClass类型,或者可以说obj.getClass()。equals(“ MyClass”)。 So i want to know are there any other ways of checking the type of an object. 所以我想知道是否还有其他方法可以检查对象的类型。

Note that the two options you cite are not equivalent: 请注意,您引用的两个选项相等:

"foo" instanceof Comparable // returns true
"foo".getClass().equals(Comparable.class) // return false

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) 当心:如果您的对象是MyClass的子类,或者如果它实现了接口, instanceof也将返回true(这通常是您感兴趣的-如果您回想起“ IS A” OOP概念)

See also this about Class.isAssignableFrom() , similar to instanceof but a little more powerful. 另请参见Class.isAssignableFrom()类似instanceof ,但更厉害一点。

instanceof是另一种选择。

instancef is not proper solution as it gives true for subclass of a class. instancef不是正确的解决方案,因为它为类的子类提供了正确的值。 Use this instead: 使用此代替:

 obj.getClass().equals("MyClass")

您可能可以通过obj.getClass().getSuperClass()递归来获得类似于instanceof东西。

As said by others, instanceof does not have the same functionality as equals . 正如其他人所说, instanceofequals具有不同的功能。

On another point, when dealing with this problem in code, using a Visitor -pattern is a clean (although not smallest in lines of code) solution. 另一方面,在代码中处理此问题时,使用Visitor模式是一种干净的解决方案(尽管在代码行中不是最小)。 A nice advantage is that once a visitor-interface has been setup for a set of classes, this can be reused again in all other places that need to handle all/some/one different extensions of a class. 一个不错的好处是,一旦为一组类设置了访问者接口,就可以在需要处理类的所有/某些/一个不同扩展的所有其他地方再次使用此接口。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM