开发者

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&l开发者_运维问答t;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
     }
}


if mes instanceof String should work.


Instead of checking INPUT, how about checking the actual parameter?

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜