How to get parametrized Class instance

前端 未结 4 1907
别那么骄傲
别那么骄傲 2020-12-20 14:30

Since generics were introduced, Class is parametrized, so that List.class produces Class. This is clear.

What I am not able to figure out is how to get a in

相关标签:
4条回答
  • 2020-12-20 15:04

    The Class class is a run-time representation of a type. Since parametrized types undergo type erasure at runtime, the class object for Class would be the same as for Class<List<Integer>> and Class<List<String>>.

    The reason you cannot instantiate them using the .class notation is that this is a special syntax used for class literals. The Java Language Specification specifically forbids this syntax when the type is parametrized, which is why List<String>.class is not allowed.

    0 讨论(0)
  • 2020-12-20 15:13

    Classes represent classes loaded by a class loader, which are raw types. To represent a parameterized type, use java.lang.reflect.ParameterizedType.

    0 讨论(0)
  • 2020-12-20 15:27

    The only thing you can do is instantiate List<String> directly and call its getClass():

    instantiate(new List<String>() { ... }.getClass());
    

    For types with multiple abstract methods like List, this is quite awkward. But unfortunately, calling subclass constructors (like new ArrayList<String>) or factory methods (Collections.<String>emptyList()) don't work.

    0 讨论(0)
  • 2020-12-20 15:28

    I don't think that you can do what you are trying. Firstly, your instantiate method doesn't know that its dealing with a parameterised type (you could just as easily pass it java.util.Date.class). Secondly, because of erasure, doing anything particularly specific with parameterised types at runtime is difficult or impossible.

    If you were to approach the problem in a different way, there are other little tricks that you can do, like type inference:

    public class GenTest
    {
        private static <E> List<E> createList()
        {
            return new ArrayList<E>();
        }
    
        public static void main(String[] args)
        {
            List<String> list = createList();
            List<Integer> list2 = createList();
        }
    }
    
    0 讨论(0)
提交回复
热议问题