简体   繁体   English

如何使用泛型类型传递 class 类型的变量

[英]How to pass variable of type class with generic type

How to pass class of ArrayList.class in the temp variable, I am getting compilation error.如何在 temp 变量中传递 ArrayList.class 的 class ,我收到编译错误。

public class Solution {

    public static void main(String args[]) {

       Class<List<String>> temp = ArrayList<String>.class;
       new A().process(temp);
    }

    static class A {
        public void process(Class<List<String>> c) {

        }
    }
}

Likely here's confusion.可能这里有混乱。 I do assume you try to instantiate an object aList of type List<String> (an instance of a class) and pass it to a method ( processObject ).我确实假设您尝试实例化List<String>类型的 object aList (类的实例)并将其传递给方法( processObject )。 But, without going into the intricacies of the type system, I also want to cover the case where you actually pass a class as a parameter of type Class to a method processClass .但是,在不涉及类型系统的复杂性的情况下,我还想介绍一下您实际上将 class 作为Class类型的参数传递给方法processClass的情况。 The things you can do with a class are rather different than those you could do with the object/instance .您可以使用class执行的操作与您可以使用object/instance执行的操作完全不同。 Looks like this.看起来像这样。

public class Solution {

    static class A {
        public static void processClass(Class c) {
            c.getName();
        }
        public static void processObject(List<String> o) {
            o.isEmpty();
        }
    }

    public static void main(String args[]) {

        List<String> aList = new ArrayList<>();
        A.processObject(aList);

        A.processObject(new ArrayList<>()); // Diamond "<>" is enough, generic type can be inferred from method signature

        A.processClass(ArrayList.class);
        A.processClass(aList.getClass());
    }

}

I do recommend to check out the basics of OO programming with java, there's plenty of stuff out there, eg this .我确实建议使用 java 查看 OO 编程的基础知识,那里有很多东西,例如这个

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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