1

Is this possible? Could I instance an object from one class or another depending on the value of a string?

I have a code like this:

public Map<Language, IConverter> converters;

// ...

public IConverter buildConverter(Language lang) {
    IConverter converter = new ???(buildMap(lang)); <---- Problem here

    converters.put(lang, converter);
}

public Map<Integer, String> buildMap(Language lang) {
    // ...
}

Where Language is a bean class containing a string which identifies a language and IConverter is an interface implemented by several (undefined amount) concrete Converter.

Do I need to add an if clause per supported Converter? Is there anyway to idenfity which string belongs to which class, maybe with a Map or something like that?

I may drop the Language class, because it is kind of shallow and can't see it scalating.

EDIT

I ended using Jesper's answer, I had to adapt my Language class for it to contain the full language name, and concatenating the package name, the languagename and "Converter".

Boy, is Reflection scary at first, so many, many Exceptions.

Alxe
  • 381
  • 3
  • 12

3 Answers3

1

If you have the name of the class in a string, you can create a new instance of it using reflection. For example:

String className = "com.mycompany.SomeConverter";

// Creates an instance of the class by using the no-args constructor
IConverter converter = (IConverter) Class.forName(className).newInstance();

If you want to use a specific constructor with arguments:

// For example, look for a constructor that takes one argument, a String
Constructor constr = Class.forName(className).getConstructor(String.class);

// Create a new instance, passing "Hello" as the argument
IConverter converter = (IConverter) constr.newInstance("Hello");
Jesper
  • 202,709
  • 46
  • 318
  • 350
  • Yes, I was looking for something like this. Sadly, I had to restructure huge parts of my little project. I'll mark this as the accepted answer. – Alxe Oct 31 '13 at 21:54
0

may be you need something very similar to this.

Dark Knight
  • 8,218
  • 4
  • 39
  • 58
0

i guess you mean this

Constructor constr = Class.forName("com.yourpackage.converter" + lang.getYourString()).getConstructor(buildMap_function_returned_class.class);

IConverter converter = (IConverter) constr.newInstance(buildMap(lang));
Apostolos
  • 10,033
  • 5
  • 24
  • 39