【发布时间】: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 中被称为泛型?
【问题讨论】:
-
你应该使用反射。看到这个:stackoverflow.com/questions/10470263/…
-
为什么不使用泛型?
public class Creator<T> { -
是否需要将子类型的实例作为ctor的参数传递?你没有用它做任何事情,所以我假设没有
-
有很多关于Java泛型的信息。做一些寻找。 docs.oracle.com/javase/tutorial/java/generics
标签: java