Instantiating classes dynamically? [duplicate]
Let's say I have this array:
String[] names = {"stack1", "stack2", "stack3"};
Is it possible t开发者_开发技巧o instantiate Stack
dynamically using those names, so there will be 3 objects named stack1
, stack2
, and stack
"? Later in the code, I'd like to call stack1.pop()
, or stack3.empty()
, for example.
I've been told to take a look at reflection, and still not sure how.
You can create objects via reflection if you have the class name in a String
, for example.
You can not "dynamically" create "variables". For example:
String s = "foo";
// some magic that creates a variable identified by s
foo.callSomeMethod();
That won't work.
Variables in Java (fields, local variables and parameters) can only be created at compile time.
What you can do (and which is sometimes the correct approach) is to create a Map<String,YourType>
and hold each newly created object via this map with a given String
:
Map<String,MyType> map = new HashMap<String,MyType>;
String s = "foo";
map.put(s, new MyType());
// ...
map.get("foo").callSomeMethod();
Unless stack1
is a class in the default package you won't be able to create classes of that "type".
If it is just a variable name, you're missing the type anyways.
Have a look at the Java Compiler API that should allow you to dynamically create sources and then compile and use them. I haven't used it myself yet, but maybe this article could help: http://www.javabeat.net/articles/73-the-java-60-compiler-api-1.html
Additionally, if you could elaborate a bit on what exactly you are trying, this would be helpful.
Why not just use a map?
Map<String, Stack<String>> m = new HashMap<String, Stack<String>>();
m.put("stack1", new Stack<String>());
m.get("stack1").push("Hello!");
精彩评论