java - When checking for a instance of the current class, why doesn't "x instanceof getClass()" work? -
i have abstract class associativefunction extends expr. there different functions subclasses of associativefunction, , there other expressions subclasses of expr not associativefunction.
in method within associativefunction class, need check if expr object instance of current class or 1 of subclasses,
i.e. product (extends associativefunction) , inherits method; therefore, check should return true product objects , crossproduct (extends product) objects, false sum (extends associativefunction) , number (extends expr) objects.
why following not work? how can work using
instanceof
operator? if can't, why not?if (newargs.get(i) instanceof getclass()) {
eclipse yields error:
syntax error on token "instanceof", == expected )
this code seems work, correct? why different (1)?
if (getclass().isinstance(newargs.get(i))) {
why following not work?
because instanceof
requires type name second operand @ compile-time, basically. won't able use instanceof
operator.
the production instanceof
operator is:
relationalexpression
instanceof
referencetype
where referencetype classorinterfacetype, typevariable or arraytype... in other words, type name rather expression evaluates class<?>
reference. you're doing bit trying declare variable type "the current class" - language isn't defined way.
this code seems work, correct?
yes.
why different (1)?
because it's using class.isinstance
method, rather instanceof
operator. they're different things. isinstance
method more dynamic version.
Comments
Post a Comment