Java中取得泛型的类型

来源:互联网 发布:java enum getname 编辑:程序博客网 时间:2024/06/04 19:57
写dao的时候可以如下方式:
package com.sourcefour.test.dao;

import java.lang.reflect.ParameterizedType;

class Person {  
//    public Person() {  
//        super();  
//    }  
  
    public void function() {  
        System.out.println("function in Person.class...");  
    }  
}  

class SubClass extends SuperClass<Person> {  

 
//    public SubClass() {  
//        super();  
//    }  
  
}  
  

public  class SuperClass<T> {

   private Class<T> clazz;
 
   @SuppressWarnings("unchecked")  
   public SuperClass() {  
   if (ParameterizedType.class.isAssignableFrom(this.getClass().getGenericSuperclass().getClass())){
    clazz = (Class<T>) ((ParameterizedType) this.getClass().getGenericSuperclass()).getActualTypeArguments()[0];
    }
   }  

 
   public Class<T> getClazz() {  
       return clazz;  
   }  
 
   public void setClazz(Class<T> clazz) {  
       this.clazz = clazz;  
   }
   
   /** 
    * 普通的非泛型类Class 
    * 泛型化的类Class<T> 
    * JDK中,普通的Class.newInstance()方法的定义返回Object,要将该返回类型强制转换为另一种类型; 
    * 但是使用泛型的Class<T>,Class.newInstance()方法具有一个特定的返回类型; 
    * @param args 
    */  
   public static void main(String[] args) {  
       SuperClass<Person> subClass = new SubClass();  
      // 1.得到泛型类T实际的完整类名  
       System.out.println(subClass.getClazz());  
       //2.得到泛型类T的对象  
       try {  
           System.out.println(subClass.getClazz().newInstance());  
       } catch (InstantiationException e) {  
           e.printStackTrace();  
       } catch (IllegalAccessException e) {  
           e.printStackTrace();  
       }  
       //3.调用泛型类T的方法  
       try {  
       subClass.getClazz().newInstance().function();  
       } catch (InstantiationException e) {  
           e.printStackTrace();  
       } catch (IllegalAccessException e) {  
           e.printStackTrace();  
       }  
   }  
}

输出结果如下: 
class myGenetic.Person 
myGenetic.Person@10d448 

function in Person.class... 

package com.sourcefour.test.dao;

但是一般这样写就悲剧了...
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
class ACE extends TestJave<String>{

}
public class TestJave<T> {
private Class<T> entityClass;
/**
* 通过反射获取子类确定的泛型类
*/
public TestJave() {
Type[] params =((ParameterizedType) this.getClass().getGenericSuperclass()).getActualTypeArguments();
}

public static void main(String[] args) {
// TestJave<?> te = new ACE(); 
TestJave<String> te = new TestJave<String>(); //运行错误!!
}
}


Exception in thread "main" java.lang.ClassCastException: java.lang.Class cannot be cast to java.lang.reflect.ParameterizedType
at com.sourcefour.test.dao.TestJave.<init>(TestJave.java:16)
at com.sourcefour.test.dao.TestJave.main(TestJave.java:21)


其中原理,暂时没有相同,还请大家知道了,点拨下...


0 0
原创粉丝点击