As far as I know, what I'm trying to do (Title) is impossible. However, here are 3 small samples of code - The first one being what I have right now, the second being what I'd like to have, the third one being a way to achieve it that I don't want to use due to reflection. I'm wondering if there is a way to restructure my code to come closer to the second example. There are a few assumptions made: Each class that will be used here has only one constructor, and knows exactly what objects it needs. The Object[] is because I don't know everything at runtime.
1.
Object o; Object[] params; String myString;
switch(myString){
case "ClassA": o = new ClassA(params);
case "ClassB": o = new ClassB(params);
//ETC
}
2.
Object o; Object[] params; String myString;
HashMap<String, Class<?>> map;
o = new map.get(myString)(params); //Obviously doesnt work
3.
Object o; Object[] params; String myString;
HashMap<String, Class<?>> map;
o = map.get(myString).getConstructors()[0].newInstance(params);
Note that I actually lied above. What I have right now is not 1
, but 3
. I can't have 1
because I can't hardcode all classnames. I'd like to have 2
though. Any suggestions?
Aucun commentaire:
Enregistrer un commentaire