从Java的许多子类中确定子类
我有一个接口 Tree
和一个实现该接口的抽象类 RBTree
。我还有几个类 Tree1
...Tree9
扩展了这个抽象类。
我编写了一个测试单元,我想做这样的事情:
public void testRandom(RBTree tree){
for(int i = 0; i < 10; i++){
rbTree = new Tree1(); //if the tree in the parameter was of instance Tree1
rbTree = new Tree2(); //if the tree in the parameter was of instance Tree2
//etc.
/**
* do something with rbTree
*/
}
}
是否可以在不使用带有大量实例的 if 语句(或开关)链的情况下执行此操作? ()?
(注意:我无法改变设计的任何内容,我知道这并不是真正的最佳选择)
I have an interface Tree
and an abstract class RBTree
which implements this interface. I also have several classes Tree1
...Tree9
which extend this abstract class.
I've written a test unit where i want to do something like this:
public void testRandom(RBTree tree){
for(int i = 0; i < 10; i++){
rbTree = new Tree1(); //if the tree in the parameter was of instance Tree1
rbTree = new Tree2(); //if the tree in the parameter was of instance Tree2
//etc.
/**
* do something with rbTree
*/
}
}
Is it possible to do this without using a chain of if-statements (or a switch) with a lot of instanceof()
?
(note: i can't change anything about the design, i know it's not really optimal)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用tree.getClass().newInstance()。
如果您想要一些比实例化更复杂的逻辑,您要么需要 instanceof 方法,要么更好 - 让每个 RBTree 子类都有一个执行该逻辑的方法(并使该方法在 <代码>RBTree)
You can use
tree.getClass().newInstance()
.In case you want to have some more complex logic than instantiation, you would either need the instanceof approach, or better - make each
RBTree
subclass have a method that performs that logic (and make that method abstract inRBTree
)试试这个:
Try this:
使用反射,您可以:
问题是,如果实际实现有不同的方法等,您将无法访问它们。
Using reflection, you can:
Problem is that if the actual implementations have different methods etc. you won't be able to access them.