简体   繁体   中英

how to check the Class Type(instanceof) in java template method?

public class Test {
    private static Object createInstance(String classPath) {
        try {
            Class<?> tClass = Class.forName(classPath);
            if (tClass != null) {
                return tClass.newInstance();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @SuppressWarnings("unchecked")
    public final static <INPUT, OUTPUT> Filter<INPUT, OUTPUT> getFilter(String path) {
        return (Filter<INPUT, OUTPUT>) createInstance(path);
    }

    public final static <INPUT, OUTPUT> OUTPUT filter(String path, INPUT mes) {
        Filter<INPUT, OUTPUT> filter = getFilter(path);

        //How to check the INPUT and OUTPUT type here?
        //if(INPUT instanceof String){ ... } not work

        return filter.filter(mes);
    }
}

refer to my earlier question here

thanks for help :)

Other answer are certainly correct. Anyway i think you are doing something quite unusual. I'll try to explain:

Generics are use for static polymorphism. An instance of a generic type is determined at compile time.

Constructs like instanceof are used to check dynamic type of an object at runtime, so if you are using them, you can simply avoid the use of generics. (You can use a generic Object as parameter for your function and then use instanceof to check its type) For example:

public void method(Object o){
    if (o instanceof String){} //do what you want
    else ....
}

Typically, if you use generics, you are just trying to avoid that constructs. Typically a generic type can implements a well know interface, in a way that any operation performed upon that object into your filter method, could be performed for different types of objects implementing that interface and without knowing the specific type of objects involved.

I don't know exactly what are the polymorphic feature that you need, anyway you could try also something like that:

public interface polymorphicObj{
     public method();
}
public class Filter<GENERIC implements polymorphicObj>{

     public filter(GENERIC obj){
           obj.method();   //you don't need to know of which specific type is polymorphicObj
     }
}

如果mes instanceof String应该可以工作。

不用检查INPUT ,而是检查实际参数呢?

if(mes instanceof String) { 

You will need instance of INPUT:

class A<INPUT>{

    void typeOf(INPUT input){
        if(input.getClass() == "".getClass()){
            System.out.println("Input is String");
        }       
    }
}

all objects extends Object co they have getClass method. You could use it to check 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