-1

I want to create interface, and x classes implementing this interface. And when the program is running I want to create new object which is instance one of this classes, which class is set in .properties file. Is it even possible ?

For example I have interface

  public interface A{
      void a();
  }

  class B1 implements A{
      void a(){}
  }

  class B2 implements A{
      void a(){}
  }

  A m = ?

And I don't know if it is possible to create object from class which is in some way define in properties?

Nominalista
  • 4,632
  • 11
  • 43
  • 102
  • 1
    "Yes". Do you have a more specific question? What have you looked at or tried, and what did or did not work? – Brett Kail May 23 '15 at 17:18
  • That question discusses only reflection as an option, which is not the only possible option to solve this. – John May 23 '15 at 18:30

2 Answers2

0

You could use if or switch block on value from property file with factory method pattern.

Or you could use reflection:

Class.forName, getConstructor and newInstance calls.

Here is an example of Factory:

public class Factory {

    public static A getA(String propertyValue) {

        switch(propertyValue) {

        case "B1": return new B1(); 
        case "B2": return new B2();
        default: throw new RuntimeException("unsupported class");

        }

    }
}

You can also cache instances of B1 and B2 if they are safe to be shared between threads, and always return these cached instances.

I would definitely opt for option with Factory if you are the one providing implementations of the interface A.

Use reflection only if you cannot solve problem in any other way. In your case, making framework for someone else who would provide their own implementations of A which would be chosen from property file. Since you wouldn't know in advance names of these classes you'd have to use reflection.

John
  • 5,189
  • 2
  • 38
  • 62
0

Yes, you can, it is very usual.

Read the property in a String like "className" and use following statement:

A a = (A)Class.forName(className).newInstance();

See this link as reference: Is there a way to instantiate a class by name in Java?

Community
  • 1
  • 1
pasaba por aqui
  • 3,446
  • 16
  • 40