我有一个简单的场景。我想在下面创建一个新类的实例。在Java中如何创建一个与'this'类相同类型的新类? Java
class A implements Fancy {
void my() {
Fancy b = // new X(); where X could be A or B
}
}
当你有一个B
它实现Fancy
为好。
我有一个简单的场景。我想在下面创建一个新类的实例。在Java中如何创建一个与'this'类相同类型的新类? Java
class A implements Fancy {
void my() {
Fancy b = // new X(); where X could be A or B
}
}
当你有一个B
它实现Fancy
为好。
与create
方法创建abstract class AbstractFancy
:
abstract class AbstractFancy implements Fancy {
abstract Fancy create();
void my() {
Fancy b = create();
//....
}
}
在每一类实现create
方法:
class A extends AbstractFancy {
Fancy create() {
return new A();
}
}
class B extends AbstractFancy {
Fancy create() {
return new B();
}
}
? (不推荐)
Fancy b = this.getClass().newInstance();
这将适用于基于零参数的构造函数(隐式或显式)。确保你在陈述中做了一个try {} catch{}
。
其他方式:
class A implements Fancy, Cloneable {
void my() {
try {
Fancy b = (Fancy) clone();
} catch (CloneNotSupportedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
或者,你想创建一个新的Fancy
对象生成器。
这将尝试实现'Fancy'界面 - 不行。 –
糟糕,这是一个界面?抱歉.... –
我假设你想在基类中定义my()
,比如FancyAdapter
,它有不同的子类,你希望它创建一个实际的具体子类的实例。如果你可以假设实现Fancy
所有类有一个默认的(无参数)构造函数:
Fancy b = (Fancy) getClass().newInstance();
class A implements Fancy {
void my() {
Fancy b = (Fancy)getClass().newInstance();
}
}
问题是什么是什么呢?为什么你不能只说花式B =新B()如果B实现花式? –
因为我不想要一个B总是我想要运行我的类型。 – rapadura
仍然不清楚你想要什么! –