Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Java] How do I convert a string into code?
#1
I'm working on something where I have to load some text from a file, parse it, and then insert that parsed text as code into an array.

For example, here's what the relevant part of my file might look like:

Code:
Recipe: new ItemStack(Item.paper, 1, 0); new ItemStack(Item.dyePowder, 1, 5);


Here's what I need the array to look like:

Code:
ItemStack[] testRecipe = ItemStack[]{new ItemStack(Item.paper, 1, 0), new ItemStack(Item.dyePowder, 1, 5)};

Here's what I would be getting with my current code:

Code:
ItemStack[] testRecipe = ItemStack[]{"new ItemStack(Item.paper, 1, 0)", "new ItemStack(Item.dyePowder, 1, 5)"};

How do I convert those strings into plain codetext? Is it even possible?
Reply
#2
Seems like you want some sort of dynamic code loading/executing, and I'm not sure how possible that is in Java. Remember, Java is not a dynamic scripting language like Lua.

That being said, I found this: http://stackoverflow.com/questions/93517...ng-to-code

Pay attention to the comments ;o
Reply
#3
Considering that the code would have to be obfuscated anyway, throwing a bit more work into it at least, I think I may end up doing a massive match-list thing that's easier for end users to understand.

Like instead of "new ItemStack(Item.paper, 1, 0)", just plain "paper" is in the config file and the code adds "new ItemStack(Item.paper, 1, 0)" to the array.
Reply
#4
Then you can either use an array/map of functions that return a new instance of ItemStacks using a similar pattern to the accepted answer to this question: http://stackoverflow.com/questions/42807...of-methods

or you could just have an array/map full of different instances of ItemStacks, depending on your needs.
Reply
#5
(07-11-2012, 03:37 PM)noob007 Wrote: Then you can either use an array/map of functions that return a new instance of ItemStacks using a similar pattern to the accepted answer to this question: http://stackoverflow.com/questions/42807...of-methods

or you could just have an array/map full of different instances of ItemStacks, depending on your needs.

Here's what I think I'm going to do. I think it's pretty inefficient, but since it's only going to be run once at start-up I don't think it's too much of an issue.

Every item is given a String name parameter. In the main Item class, there is an array that every item gets added to. It's 32,000 long. My code will skim through the array, and if there is an item in that slot, it checks to see if the name parameter of the Item matches the given string. Because some items have a metadata or damage value (like dyes) in one Item object, I'll also manually add in a list for certain names. It'll then take that Item and add it to the recipe array as an ItemStack.
Reply


Forum Jump:


Users browsing this thread: 2 Guest(s)