java - instanceof vs equals on defined string that identifies the Class -
i can test class type in program i'm working both instanceof or getting field identifies class appartenency. choice between
if(myobjec instanceof something){ } and
if(myobjec.geclasstype().equals("something")){ } what best in terms of efficency?
geclasstype() method present in object of program i'm working(not standard java method) , method returns string wih name of class. name passed field when object created
edit field in second sample in code doesn't identify class category , used different routines, can use purpose since use specific object each category. have reported getclasstype make question more clear.
you mean what's difference if verifying if object reference belongs specific class using instanceof vs comparing name of class.
instanceof works object references class or subclass of class being compared. in case of interfaces, returns true if class (or super class) of object reference implements interface.
getclass().getname().equals("nameoftheclass") (masked getclasstype method) verify if class of object reference exactly class, sub class won't pass test.
which 1 use? use 1 better suits case:
if want/need use object references belongs class or interface, despite if class of object reference subclass or implements interface, use
instanceof. example, when iterating through elements ofcollectionverify if objects implement desired interface.if need determine if class of object reference exactly specific class, use
getclass().getname().equals("..."). example, when implementingequalsmethod in class should compare elements belongs class (no subclasses allowed). ides when auto generatingequalsmethod.
still, better option getclass().getname().equals("...") getclass().equals(theclass.class).
in terms of efficiency, if need verify if object belongs specific class only, use getclass().equals(theclass.class) rather getclass().getname().equals("...") because 1 compare references (which fast instanceof). if have class name, use current approach. not worry performance of application because jit optimize code @ runtime after several executions of code. still, f think statement may performance bottleneck, prove using profiler.
Comments
Post a Comment