I have an abstract class AssociativeFunction which extends Expr. There are different functions which are subclasses of AssociativeFunction, and there are other expressions which are subclasses of Expr but not AssociativeFunction.
In a method within the AssociativeFunction class, I need to check if an Expr object is an instance of the current class or one of its subclasses,
i.e. Product (extends AssociativeFunction) and inherits this method; therefore, the check should return true for all Product objects and all CrossProduct (extends Product) objects, but false for all Sum (extends AssociativeFunction) and Number (extends Expr) objects.
Why does the following not work? How can I get this to work using the instanceof operator? If I can't, why not?
if (newArgs.get(i) instanceof getClass()) {
Eclipse yields the error:
Syntax error on token "instanceof", == expected )
This code seems to work, is that correct? Why is it different than (1)?
if (getClass().isInstance(newArgs.get(i))) {
Why does the following not work?
Because instanceof requires a type name as the second operand at compile-time, basically. You won't be able to use the instanceof operator.
The production for the instanceof operator is:
RelationalExpression
instanceofReferenceType
where ReferenceType is a ClassOrInterfaceType, TypeVariable or ArrayType... in other words, a type name rather than an expression which evaluates to a Class<?> reference. What you're doing is a bit like trying to declare a variable whose type is "the current class" - the language just isn't defined that way.
This code seems to work, is that correct?
Yes.
Why is it different than (1)?
Because it's using the Class.isInstance method, rather than the instanceof operator. They're simply different things. The isInstance method is effectively a more dynamic version.
This method is the dynamic equivalent of the Java language instanceof operator.
I take that to mean that isInstance() is primarily intended for use in code dealing with type reflection at runtime. In particular, I would say that it exists to handle cases where you might not know in advance the type(s) of class(es) that you want to check for membership of in advance (rare though those cases probably are).
For instance, you can use it to write a method that checks to see if two arbitrarily typed objects are assignment-compatible, like:
public boolean areObjectsAssignable(Object left, Object right) {
return left.getClass().isInstance(right);
}
In general, I'd say that using instanceof should be preferred whenever you know the kind of class you want to check against in advance. In those very rare cases where you do not, use isInstance() instead. Hope this helps!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With