Reputation: 99
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?
Some clarifications:
The HashMap in examples 2
and 3
contains pairs of string representations of the classname, and actual class-objects.
Also, it is filled at runtime (Obviously), meaning that I know of all possible classes I would want to instantiate before executing the code above, however I can't hardcode any of them: They're loaded by file.
Upvotes: 0
Views: 609
Reputation: 4586
I am sorry to inform:
it is not possible in Java.
Write your own language that does not follow the principle of bivalence, where you can instantiate a class with reflection but without use of reflection. Good luck.
Upvotes: 1