开发者

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"). So i want to know are there any other ways of checking the type of an object.


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)

See also this about Class.isAssignableFrom(), similar to instanceof but a little more powerful.


Note that the two options you cite are not equivalent:

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


Class#isAssignableFrom(java.lang.Class) is another option.


instanceof is another option.


You could probably recurse through obj.getClass().getSuperClass() to get something similar to instanceof.


As said by others, instanceof does not have the same functionality as equals.

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. 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.


instancef is not proper solution as it gives true for subclass of a class. Use this instead:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜