How to get parametrized Class instance

前端 未结 4 1910
别那么骄傲
别那么骄傲 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: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  List createList()
        {
            return new ArrayList();
        }
    
        public static void main(String[] args)
        {
            List list = createList();
            List list2 = createList();
        }
    }
    

提交回复
热议问题