java 根據泛型創建對象,實例化泛型對象

實例化泛型對象

在你發佈的代碼中,不可能創建一個泛型T,因爲你不知道它是什麼類型:

public class Abc<T>
{
       public T getInstanceOfT()
       {
           // There is no way to create an instance of T here
           // since we don't know its type
       }
} 

當然,如果你有一個引用Class<T>並且T有一個默認的構造函數,就可以調用newInstance()這個Class對象。

如果你繼承子類,Abc<T>你甚至可以解決類型擦除問題,並且不必傳遞任何Class<T>引用:

import java.lang.reflect.ParameterizedType;

public class Abc<T>
{
	private T getInstanceOfT()
	    {
	        ParameterizedType superClass = (ParameterizedType) getClass().getGenericSuperclass();
	        Class<T> type = (Class<T>) superClass.getActualTypeArguments()[0];
	        try
	        {
	            return type.newInstance();
	        }
	        catch (Exception e)
	        {
	            // Oops, no default constructor
	            throw new RuntimeException(e);
	        }
	    }
	
	    private Class<T> getClassOfT()
	    {
	        ParameterizedType superClass = (ParameterizedType) getClass().getGenericSuperclass();
	        Class<T> type = (Class<T>) superClass.getActualTypeArguments()[0];
	        return type;
	    }

class SubClass
    extends Abc<String>
{
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章