简体   繁体   中英

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

How do I encapsulate code that uses 'instanceof' , I have a lot of types to judge, how do I simplify them? For example using for loops.

            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 :】

My idea is: add the classes you want to judge to a ignoreList collection and iterate using Instanceof. But have error:Cannot resolve symbol 'get'

public boolean shouldIgnore(Object obj) {

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

You can use Class objects and use the isInstance method to check if an object is an instance of a particular class:

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

You would use it like this:

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

If you prefer to use List<Class<?>> instead of an array, it works just as well. Change the method signature to:

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

and invoke it like:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM