instanceof use for multiple types

元气小坏坏 提交于 2019-12-10 16:47:28

问题


I am writing a TypeChecker for MiniJava and ExpOp needs to check if both of the entered expressions are of Integer to use plus, minus, times.

How can I write a line of code inside an if statement that includes both expressions and checks if both of them are instances of (instanceof) Integer?

This is what I have now:

n.e1.accept(this) n.e2.accept(this) instanceof Integer

Appreciate your help.


回答1:


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?




回答2:


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



回答3:


In case you have a situation where instanceof EITHER of the classes will suffice your needs you can use the || (logical OR) operator:

if (n.e1.accept(this) instanceof Integer ||
n.e2.accept(this) instanceof Boolean) {
...
}


来源:https://stackoverflow.com/questions/15981402/instanceof-use-for-multiple-types

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!