2013-12-16 61 views
1

是否可以聲明存儲在集合中的類型(文字)的變量? 或者這可能更多地是解釋的特性/任務,而不是像Java這樣的編譯語言?聲明存儲在集合中的類型(文字)的變量

例如:

import java.util.*; 

class Base {} 
class A1 extends Base{} 
class A2 extends Base{} 

public class Test{ 

    public static void main(String[] args){ 

     ArrayList<Class<? extends Base>> typeArrayList=new ArrayList<Class<? extends Base>>(); 
     typeArrayList.add(A1.class); 
     typeArrayList.add(A2.class); 
     typeArrayList.add(A1.class); 
     typeArrayList.add(A1.class); 
     //etc. etc. 

     //now that all the types are nicely stored in a collection, 
     //could we somehow use them to declare variables of those types? 
     //e.g. declare something like: 
     //typeArrayList.get(1) someVariable; 

    }//main 
}//Testlass 

回答

2

您可以使用:

Object o = typeVarArrayList.get(1).newInstance(); 

Type o = (Type) typeVarArrayList.get(1).newInstance(); 

但你需要一個類具有不帶參數的一個構造。

如果您需要更具體的構造方法,請參閱here

+0

謝謝AVolpe,這有助於創建存儲類型的對象。關於原始問題(聲明這些類型的變量) 第一個解決方案聲明Object類型的變量, ,而第二個解決方案需要知道存儲在集合元素中的類型,以便我可以向下轉換爲該類型。 – Pedja

+0

重新閱讀你的問題之後,我認爲你唯一的方法就是使用Reflection來調用方法,編譯器不可能知道'List'的什麼位置。乾杯 –

1

您可以使用newInstance()如果有一個默認的構造函數可用,如果沒有,那麼你就需要讓人們與工廠對象提供給您,然後調用一個方法在工廠建立你的對象。

對於大多數實現來說,工廠模式通常更加整潔,除非創建的對象確實只是純白色的只有默認值的普通bean,因爲工廠允許您正確設置對象。

1
//e.g. declare something like: 
    //typeArrayList.get(1) someVariable; 

總之,不,類型聲明必須是顯式的。

例如,Java language定義了這些規則,局部變量聲明:

LocalVariableDeclaration: 
VariableModifiersopt Type VariableDeclarators 

Type: 
PrimitiveType 
ReferenceType 

ReferenceType: 
ClassOrInterfaceType 
TypeVariable 
ArrayType 

追溯至的TypeVariable(因爲我沒有複製整個語言的語法),我們得到:

TypeVariable: 
Identifier 

identifier僅限於您期望的課程名稱。