0

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?

9
  • I am not sure what exactly confuses you. You call the constructor using newInstance, provide your arguments, like newInstance("test") and then you have to manually cast, like (A) Class.forName(...).... Commented Feb 9, 2020 at 12:49
  • If you insist on casting to the child class: First, get the object. Then check the type using "instance of" and cast. Commented Feb 9, 2020 at 12:49
  • Note that instanceof is obsolete if B extends A. Commented Feb 9, 2020 at 12:50
  • @Zabuza it's still good practice to use it, as you can't know for sure whether the string in the configuration is for a class that actually extends A, and you may want to handle that before an exception is thrown. Commented Feb 9, 2020 at 12:52
  • 2
    It would be better to test the loaded class with isAssignableFrom before running the constructor, though, rather than use instanceof, as the constructor may have unwanted side effects in case it's not the appropriate class. Commented Feb 9, 2020 at 12:58

2 Answers 2

1

Just cast it to A:

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

You don't need to know the exact class.

Sign up to request clarification or add additional context in comments.

2 Comments

isn't type of the instance in that case A? I always need the instance of the class that i define in a config, since it may also have additional methods and members
No, the real type is not A, it's some class that extends A. If you write Object o = "string", the real type of o is String, not Object. There is a difference beween declared type and actual type.
-1

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();
    }
}

1 Comment

the solution could work, but i always have to extend this code whenever i have a new subclass of A. I want to avoid that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.