簡體   English   中英

多種類型的使用實例

[英]instanceof use for multiple types

我正在為 MiniJava 編寫 TypeChecker,ExpOp 需要檢查輸入的兩個表達式是否都是整數以使用加號、減號、時間。

如何在包含兩個表達式的if語句中編寫一行代碼並檢查它們是否都是 ( instanceof ) Integer instanceof

這就是我現在所擁有的:

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

感謝您的幫助。

您可以創建一個使用instanceof的反射對應物Class.isInstance()的實用函數:

public static boolean allInstanceOf(Class<?> cls, Object... objs) {
    for (Object o : objs) {
        if (!cls.isInstance(o)) {
            return false;
        }
    }
    return true;
}

像這樣使用它:

allInstanceOf(String.class, "aaa", "bbb"); // => true
allInstanceOf(String.class, "aaa", 123); // => false

instanceof是一個二元運算符:它只能有兩個操作數。

解決您問題的最佳解決方案是 Java 的布爾 AND 運算符: &&

它可用於計算兩個布爾表達式: <boolean_exp1> && <boolean_exp2> 當且僅當在評估時兩者都為true時才返回true

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

話雖如此,另一種可能的解決方案是將它們都投射到try / catch塊中,當其中一個不是Integer將拋出ClassCastException

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
}

但不建議這樣做,因為它是一種稱為Programming By Exception的已知反模式。

我們可以向您展示一千種方法(創建方法、創建類和使用多態性),您可以用一行來做到這一點,但沒有一種比使用&&運算符更好或更清晰 除此之外的任何事情都會使您的代碼更加混亂且難以維護。 你不想要那個,是嗎?

如果您遇到類的instanceof EITHER 滿足您的需求的情況,您可以使用|| (邏輯或)運算符:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM