How do I get a class instance of generic type T?

前端 未结 22 1578
猫巷女王i
猫巷女王i 2020-11-21 11:03

I have a generics class, Foo. In a method of Foo, I want to get the class instance of type T, but I just can\'t call T.

22条回答
  •  轮回少年
    2020-11-21 11:54

    Many poeple don't know this trick! Actually, I just found it today! It works like a dream! Just check this example out:

    public static void main(String[] args) throws NoSuchMethodException {
        Date d=new Date();  //Or anything you want!
        printMethods(i);
    }
    
    public static  void printMethods(T t){
        Class clazz= (Class) t.getClass(); // There you go!
        for ( Method m : clazz.getMethods()){
            System.out.println( m.getName() );
        }
    }
    

提交回复
热议问题