2013-12-16 64 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仅限于您期望的课程名称。