在 Java 中,如何创建与“this”类型相同的新类?班级?爪哇
我有一个简单的场景。我想创建下面的类的一个新实例。
class A implements Fancy {
void my() {
Fancy b = // new X(); where X could be A or B
}
}
当您有一个也实现了 Fancy
的 B
时。
I have a simple scenario. I'd like to create a new instance of the class below.
class A implements Fancy {
void my() {
Fancy b = // new X(); where X could be A or B
}
}
When you have a B
which implements Fancy
as well.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

发布评论
评论(4)
黑色毁心梦2024-12-09 14:11:47
反思性的? (不推荐)
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
对象的构建器。
~没有更多了~
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
使用
create
方法创建一个抽象类 AbstractFancy
:在每个类中实现
create
方法:Create an
abstract class AbstractFancy
with acreate
method:In each class implement the
create
method: