簡體   English   中英

如何封裝這個使用“instanceof”的 java 代碼?

[英]How do I encapsulate this java code that uses 'instanceof'?

如何封裝使用了'instanceof'的代碼,我要判斷的類型很多,如何簡化? 例如使用 for 循環。

            if (obj instanceof UserLogin) {
                continue;
            }
            if (obj instanceof MultipartFile) {
                continue;
            }
            if (obj instanceof Part) {
                continue;
            }
            if (obj instanceof HttpServletRequest) {
                continue;
            }
            if (obj instanceof HttpServletResponse) {
                continue;
            }


   //【Simplify using for loops :】

我的想法是:將你要判斷的類加入到一個ignoreList集合中,使用Instanceof進行迭代。 但是有錯誤:無法解析符號'get'

public boolean shouldIgnore(Object obj) {

    for (int i = 0; i < ignoreList.size(); i++) {
        if (obj instanceof ignoreList.get (i) ){
            return true;
        }
    }
    return false;
}

您可以使用Class對象並使用isInstance方法檢查 object 是否是特定 class 的實例:

public static boolean shouldIgnore(Object obj, Class<?>[] ignoreList) {
    for (Class c : ignoreList) {
        if (c.isInstance(obj)) {
            return true;
        }
    }
    return false;
}

你會像這樣使用它:

shouldIgnore(new Integer(10), new Class<?>[] { Number.class, String.class })

如果您更喜歡使用List<Class<?>>而不是數組,它也同樣有效。 將方法簽名更改為:

public static boolean shouldIgnore(Object obj, List<Class<?>> ignoreList) 

並像這樣調用它:

shouldIgnore(10, List.of(Number.class, String.class))

暫無
暫無

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

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