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)
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
RBTreesubclass have a method that performs that logic (and make that method abstract inRBTree)