instanceof use for multiple types
You can make a utility function that uses the reflection counterpart of instanceof
, Class.isInstance()
:
public static boolean allInstanceOf(Class<?> cls, Object... objs) {
for (Object o : objs) {
if (!cls.isInstance(o)) {
return false;
}
}
return true;
}
You use it like this:
allInstanceOf(String.class, "aaa", "bbb"); // => true
allInstanceOf(String.class, "aaa", 123); // => false
instanceof
is a binary operator: it can only have two operands.
The best solution for your problem is Java's boolean AND operator: &&
.
It can be used to evaluate two boolean expressions: <boolean_exp1> && <boolean_exp2>
.
Will return true
if and only if both are true
at the time of the evaluation.
if (n.e1.accept(this) instanceof Integer &&
n.e2.accept(this) instanceof Integer) {
...
}
That being said, another possible solution is to cast them both inside a try
/catch
block, and when one of them is not an Integer
a ClassCastException
will be thrown.
try {
Integer i1 = (Integer) n.e1.accept(this);
Integer i2 = (Integer) n.e2.accept(this);
} catch (ClassCastException e) {
// code reached when one of them is not Integer
}
But this is not recommended as it is a known anti-pattern called Programming By Exception.
We can show you a thousand ways (creating methods, creating classes and using polymorphism) you can do that with one line, but none of them will be better or clearer than using the &&
operator. Anything other than that will make you code more confusing and less maintainable. You don't want that, do you?