Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determining implementing class based on some condition in Java

Tags:

java

class

I'm having an interface "Parent", and multiple classes (say Abc.java, Def.java, and Xyz.java) implementing the interface. Now I want to do something like this:

Parent factoryMethod(String condition){
    Parent p = null;
    if(condition.equals("Abc"))
        p = new Abc();
    else if(condition.equals("Def"))
        p = new Def();
    else if(condition.equals("Xyz"))
        p = new Xyz();
    return p;
}

Basically I'm passing the name of the class to be instantiated as the parameter to the method. What is the best way to be doing this? Should I use reflection for this? Its not just 3 classes, there might be a lot more. So I don't want to write if/else.

Thanks.

like image 755
drunkenfist Avatar asked Sep 28 '22 18:09

drunkenfist


1 Answers

One way is to define the method as a generic one, with a type parameter extending Parent, and then create the instance by reflection:

<T extends Parent> T factoryMethod(Class<T> clazz) throws Exception {
    return (T) clazz.newInstance();
}

You can then use the method as follows:

Abc abc = obj.factoryMethod(Abc.class);
Def def = obj.factoryMethod(Def.class);

// The below won't compile if SomeOtherClass does not implement Parent
SomeOtherClass instance = obj.factoryMethod(SomeOtherClass.class); 

However this assumes that all subclasses of Parent have no-argument constructor (either they define a no-argument constructor or they don't define any constructor, hence having a default constructor available).

like image 64
M A Avatar answered Oct 30 '22 18:10

M A