Reputation: 1479
i have string contain the name of class which i need to define it ,
// this is the name of language class which i need to define it
String language = "english";
i can define it as :
english eng = new english();
but this method is for fixed names , but in my case , the string "language" may change to another class name , for example next time may be as :
String language = "french";
so i need to know a dynamic method to define the class of "language" string , to load any class with out using fixed method of defining such as :
french eng = new french();
Upvotes: 0
Views: 83
Reputation: 597274
You can, but you shouldn't.
The quick solution is reflection. You can do Class.forName(className)
and the class will be located (note that it should also include a package)
The better solution is to provide another mechanism for creation - factory, for example, and an interface common to all languages.:
interface Language { .. }
public class English implements Language { .. }
public class French implements Language { .. }
public class LanguageFactory {
private static Map<String, Language> languageRegistry;
public static Language createLanguage(String name) {
return languageRegistry.get(name);
}
public synchronized void init() {
//populate the registry
}
}
(the registry is initialized once, by calling .put("english", new English())
Upvotes: 2
Reputation: 6003
public class Language{
String name;
public Language(String name){
this.name=name;
}
}
caller:
Language english = new Language("English");
But if you are not starting from scratch and the classes already exist, use reflection.
Upvotes: 1