采用类和同一个类实例的方法,否则编译时错误

时间:2019-04-19 03:47:24

标签: java generics

采用类和同一个类的实例的方法否则会编译时错误。

类似

public void someMethod(Class classType, ClassType instanse )

例如

someMethod(String.class, "a instance of class") ==> compile ok
someMethod(String.class, new Integer(1)) ==> compile error

2 个答案:

答案 0 :(得分:2)

您可以这样做:

public <T> void foo(Class<T> classVar, T instance) {
    //....
}

然后调用:

foo(String.class, "An instance!");      //Compiles
foo(String.class, new Integer(0));      //The method foo(Class<T>, T) is not applicable for the arguments (Class<String>, Integer)
foo(Integer.class, new Integer(0));     //Compiles

答案 1 :(得分:0)

找到这样的解决方案:

public class GenericDemo<E> {
    public static void main(String[] args) {
        new GenericDemo<String>().classDemo(String.class, "abc");
        # new GenericDemo<String>().classDemo(String.class, new Integer(2)); # give compile time error
    }

    public void classDemo(Class<? extends  E> clazz, E e){

    }
}