Home > Software design >  How do I encapsulate this java code that uses 'instanceof'?
How do I encapsulate this java code that uses 'instanceof'?

Time:02-24

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;
}

CodePudding user response:

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))
  • Related