简体   繁体   English

声明存储在集合中的类型(文字)的变量

[英]Declare variable of a type (literal) stored in a collection

Is it possible to declare variable of a type (literal) stored in a collection? 是否可以声明存储在集合中的类型(文字)的变量? Or that might be more of a feature/task for an interpreted, not a compiled language like Java? 或者这可能更像是解释的特征/任务,而不是像Java这样的编译语言?

For example: 例如:

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

You can use: 您可以使用:

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

or 要么

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

But you need that the class have one constructor without parameters. 但是你需要该类有一个没有参数的构造函数。

If you need a more specific constructor, please see here 如果您需要更具体的构造函数,请参阅此处

You can use newInstance() if there is a default constructor available, if not then you will need to have people supply you with factory objects and then call a method in the factory to build your objects. 如果有可用的默认构造函数,则可以使用newInstance() ,如果没有,则需要让人们为您提供工厂对象,然后在工厂中调用方法来构建对象。

The Factory pattern is generally neater too for most implementations unless the objects being created really are just plain beans with nothing but default values as the factory allows you to properly set up the object. 对于大多数实现,Factory模式通常也更整洁,除非正在创建的对象实际上只是普通的bean而只有默认值,因为工厂允许您正确设置对象。

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

In short, no, type declarations must be explicit. 简而言之,不,类型声明必须是明确的。

For example, the Java language defines these rules for local variable declarations: 例如, Java语言为局部变量声明定义了这些规则:

LocalVariableDeclaration:
 VariableModifiersopt Type VariableDeclarators

Type:
 PrimitiveType
 ReferenceType

ReferenceType:
 ClassOrInterfaceType
 TypeVariable
 ArrayType

Drilling down to TypeVariable (because I'm not copying the entire language grammar) we get: 深入研究TypeVariable (因为我没有复制整个语言语法)我们得到:

TypeVariable:
 Identifier

An identifier is restricted to the things you'd expect in a class name. 标识符仅限于您在类名中所期望的内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM