【问题标题】:How to create many objects by passing the object type?如何通过传递对象类型来创建多个对象?
【发布时间】:2014-01-17 15:05:00
【问题描述】:

我有一个类,我们称之为 Creator,它包含两个实例字段。这些字段属于父类 A。在 Creator 的构造函数中,我想传递类 A 的子类,然后从传递的类型创建两个对象并将引用分配给这两个字段。我怎么能做这样的事情?我不知道如何进行这种概括。

编辑:类 Creator 应接受 A 或 A 本身的子类型。所以不是任何其他通用类型。 AND A 没有无参数构造函数

所以像这样,这里的 GeneralClassifier 是 A 并且没有无参数的构造函数:

public class TwoLevelClassifier <T> {

    private GeneralClassifier firstCl, secondCl;

    //The passed type shall *only* be a GeneralClassifier or a child of it
    public TwoLevelClassifier( GeneralClassifier cl ) {
        firstCl = //create a new classifier that is of the type passed to the constructor
        secondCl = //create a new classifier that is of the type passed to the constructor
    }

}

我不确定,但也许这个特性在 java 中被称为泛型?

【问题讨论】:

标签: java


【解决方案1】:

您可以使用反射来做到这一点:

public class Creator<A> {
    A a, b;

    public Creator(Class<A> childrenType) throws IllegalAccessException, InstantiationException {
        a = childrenType.newInstance();
        b = childrenType.newInstance();
    }
}

注意:这假定您使用的类具有无参数构造函数。

编辑您对原始问题进行了大量编辑。

对于A 类型只能是GeneralClassifier 或其子类的要求,请在类型参数中添加约束:

public class Creator<A extends GeneralClassifier> {

对于 A 类没有无参数构造函数的要求:然后您必须查找要使用的构造函数并使用适当的参数调用它。你必须事先知道你必须调用什么构造函数。假设您要调用一个采用String 的构造函数。那么它会是这样的:

Constructor<A> constr = childrenType.getConstructor(String.class);
a = constr.newInstance("Hello");
b = constr.newInstance("Bye");

请参阅类java.lang.Class 和包java.lang.reflect 的API 文档。

【讨论】:

  • 答案还可以,但我要指出的是,使用反射应该永远是最后的手段。
  • 泛型和反射是一回事吗?
  • 不,genericsreflection
  • 为什么不a = new A();
  • @crush 因为那不起作用,A 是类型参数,而不是具体类型。
【解决方案2】:

你可以用反射和泛型做类似的事情,就像这样

// <TYPE> is the generic type.
public class Creator<TYPE> {
    TYPE a = null, b = null;

    public Creator(Class<TYPE> childrenType) {
        try {
            // newInstance is reflection.
            a = childrenType.newInstance();
            b = childrenType.newInstance();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }
}

或者,你可以通过传入TYPE的实例来避免反射,使用这个构造函数(例如)-

public Creator(TYPE a, TYPE b) {
    this.a = a;
    this.b = b;
}

【讨论】:

  • 你能解释一下newInstance()是如何使用反射的吗?
  • @Octopus 因为它需要运行时检查,阅读the javadoc 特别注意异常。
  • @ElliottFrisch 感谢您的路线和解释!
猜你喜欢
  • 1970-01-01
  • 2012-11-27
  • 1970-01-01
  • 1970-01-01
  • 2016-11-11
  • 2016-05-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多