开发者_JS百科I have a superclass and child classes.
I am in a child class and in a super method I want to check if a certain parameter object is of the certain child class.I want something like
if (MyObj instanceof this)
what is the most efficient way to do it? I know I can do
if (MyObj.getClass.equals(this.getClass)
But that isnt too eficient
Referencing subclasses in superclass methods is indicative of a design problem in need of refactoring. While you can do it (if (this instanceof SubClass)
), it tightly couples the superclass to the subclass(es). In class-based OOP, subclasses are of course tightly coupled to the superclass (inheriting is inherently tightly-coupling), but the converse is rarely true and almost never appropriate.
In terms of efficiency, if (this instanceof SomeClass)
is fine.
Edit: From your edit, it almost seems like you're trying to find out in the superclass's method whether it's being called on an instance whose final run-time class is the superclass, and not a subclass. That's a slightly different thing, and AFAIK the most efficient way to do it pretty much as you've quoted:
if (this.getClass().equals(TheClass.class))
It still suggests that the class wants to be refactored a bit, though.
Edit 2: But from your comment on the question, it sounds like you want to compare it with the class of a member you're holding. If the member is an instance of the class itself, use the above. If it may vary, then:
if (this.getClass().equals(theMember.getClass()))
Remember the difference between getClass and instanceof. instanceof will work if your object inherits from the class you're comparing it to, the comparison with getClass will not. So if you use getClass you will be cutting yourself off from being able to extend that subclass, while with instanceof you will still be able to make new subclasses of the subclasses without breaking this code. So you should consider whether the efficiency of using equals and getClass() is worth painting yourself into a corner.
精彩评论