简体   繁体   中英

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.

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 ). 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 . The things you can do with a class are rather different than those you could do with the 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 .

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