2012-08-31 44 views
0

我有我的通用接口:Java泛型運行時實例

public interface myGenericInterface<T> {...} 

而且我有一個類檢索這樣:

Class<?> myClass = Class.forName("myClassName"); 

我希望能夠實例是這樣的:

myGenericInterface<myClass> mySubType ... 

當然不行。有沒有辦法做這樣的事情?

UPDATE:

好吧,既然泛型是有關編譯時我想它不會與反射式的代碼工作。所以沒有什麼可以解決的。

+3

我不明白你要完成什麼。你能否擴展你對最終目標的描述?也許是一個完整的代碼片段,顯示你希望你能做什麼? –

+2

你的意思是'myGenericInterface mySubType =(myGenericInterface )myClass.newInstance();'? – assylias

回答

2

泛型是一個編譯時間功能,有助於避免編程錯誤,所以你試圖做的沒有道理,抱歉。

+0

我同意:)謝謝 – forhas

1

當您在類字段中聲明具有泛型的對象時,則此類中的字段反射對象會保留聲明的通用類型。

static class ClassA { 
    public List<String> field = new ArrayList<String>(); 
} 

public static void main(String[] args) throws Exception { 
    Field field = ClassA.class.getField("field"); 
    Class<?> genericType = getGenericType(field); 
    System.out.println(genericType); 
} 

private static Class<?> getGenericType(Field field) { 
    final Type type0 = field.getGenericType(); 
    if (type0 instanceof ParameterizedType) { 
     final Type type = ((ParameterizedType) type0).getActualTypeArguments()[0]; 
     if (type instanceof Class<?>) { 
      return (Class<?>) type; 
     } 
     // miss code for method arguments 
    } 
    return Object.class; 
} 

代碼打印class java.lang.String並且可以在你的情況下有用,但基本原料類對象不攜帶仿製藥信息 - 作爲泛型信息只在編譯的時候,而不是運行時的時間。