hotfix
hotfix

Reputation: 3396

How can I dynamically create an instance of a class in java?

I would like to create an object dynamically.

I have the following structure: 1 abstract class and several classes that inherit from the abstract class

abstract public class A {..}


public class B extends A{..}
public class C extends A{..}

I have a config file where i want to add a class name, to have the ability to control which class it should be used.

# config class name
 classname = B

I tried the following, but here I have the problem that I have to cast the result and I do not know how I can do it dynamically at this point

public class TestClass {

  public A instB;

  public void getInstance(){
    this.instB = Class.forName("B") /*here i put later the config value classname*/
    .getConstructor(String.class)
    .newInstance(new Object[]{"test"});   // <--- How to cast this dynamicly to a class in the config?
  }
}

How can I dynamically create an instance of a class?

Upvotes: 0

Views: 3489

Answers (2)

momo
momo

Reputation: 3551

I don't see the point of why you really need to use reflection. I would suggest using a simple strategy pattern, for example:

Strategy.java

public interface Strategy {
    void doWork();
}

StrategyA.java

public class StrategyA implements Strategy {
    @Override
    public void doWork() {
    }
}

Strategy B.java

public class StrategyB implements Strategy {
    @Override
    public void doWork() {
    }
}

Main.java

public class Main {

    public static void main(String[] args) {
        // read the option from a config file
        String option = "B";
        Strategy strategy = createStrategy(option);

        // create a context with the strategy
        MyContext context = new MyContext(strategy);
        context.doWork();

        // config has changed dynamically, change the strategy
        context.useStrategy(new StrategyA());
        context.doWork();
    }

    public static Strategy createStrategy(String strategy) {

        if (strategy.equals("A")) {
            return new StrategyA();
        }

        return new StrategyB();
    }
}

MyContext.java

public class MyContext {
    Strategy strategy;

    public MyContext(Strategy strategy) {
        this.strategy = strategy;
    }

    public void useStrategy(Strategy strategy) {
        this.strategy = strategy;
    }

    public void doWork() {
        strategy.doWork();
    }
}

Upvotes: -1

Olivier
Olivier

Reputation: 18220

Just cast it to A:

instB = (A)Class....newInstance(...);

You don't need to know the exact class.

Upvotes: 1

Related Questions