Reputation: 251
This is the final result Im aiming to get:
ItemStack block = new ItemStack(Block.dirt, 1);
And this is what I have
String s = "Block.dirt";
ItemStack block = new ItemStack( , 1);
It kinda looks impossible, but is there a way to turn the string "Block.dirt" into Block.dirt?
I tried many things, some people suggested me to use GroovyShell and Binding but I cannot do that.
Is there a way to name a object from a string?
Any help is highly appreciated. Thank you.
Can I have an example?
Upvotes: 1
Views: 105
Reputation: 121881
Sure - people do it all the time. For example, when they open a JDBC connection object.
You want "class.forName()":
http://www.theserverside.com/news/1365412/Understanding-ClassforName-Java
Within Java, dynamic-loading is typically achieved by calling the forName method on the class java.lang.Class
Here's an article on "Reflection" in general:
http://java.sun.com/developer/technicalArticles/ALT/Reflection/
Upvotes: 1
Reputation: 160321
Why can't you do that? Or use an evaluation engine like MVEL etc?
In any case, you can split up the string, instantiate based on class name, and use reflection to call the method. Or, in this case, call a static method, based on the snippet you provide.
Without knowing what you've actually tried that didn't work, not sure how else to help.
Upvotes: 1