Aerus
Aerus

Reputation: 4380

Determining subclass out of a lot of subclasses Java

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)

Upvotes: 1

Views: 89

Answers (3)

Bozho
Bozho

Reputation: 597076

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 in RBTree)

Upvotes: 3

Pieter
Pieter

Reputation: 3399

Using reflection, you can:

string name = tree.getClass().getName()
Class.forName(name).newInstance();

Problem is that if the actual implementations have different methods etc. you won't be able to access them.

Upvotes: 1

socha23
socha23

Reputation: 10239

Try this:

rbTree = tree.class.newInstance();

Upvotes: 2

Related Questions