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.