Reputation: 341
I am currently making a game. In this game, there is a class called "Tile" that has a list of all tiles in this format:
public static final Tile <TILE_NAME> = new BasicTile<BasicSolidTile>(id, SpriteSheetX, SpriteSheetY, 0xFFColorInMap, isBackground, isLiquid);
One of the main aspects of this game is the ability to "mod" it at will (There will be a mod.smf file that has declarations of modding). In this file, you will create a new Tile like this:
--Tile--
BasicTile/BasicSolidTile <Name>: X,Y,HexColor,<Background/Foreground>,<NotLiquid/Liquid>
The ID will be calculated in the code.
I was wondering how I would create more "public static final Tile's" in my Tile class using a for loop running through all the new Tiles in the mod file. Is it possible, or will I have to change how the Tile's are stored (An ArrayList for instance?)?
Upvotes: 2
Views: 104
Reputation: 8715
ArrayList
would be the best choice. But just in case: here is some possibilities, how you can dynamically add fields (or change existing classes at runtime otherwise):
You can get the byte code of your class from the classloader and then use ASM-libaray to modify your class. The modified byte code can be load then into your JVM using custom class loader. After that you will have two different copies of you class loaded at the same time. To call methods on the modified and not on the original class you will have to use Reflection API.
To have only one (modified) copy of your class you can implement Java-Agent. Using Java-Agent you can modify byte code before loading into Java Virtual Maschine. ASM makes this task relatively easy.
You can also generate Java code from your mod file, compile it and then load it into JVM. In order to compile Java code at runtime with javac
you will need JDK. But most ordinary uses have only JRE installed. A nice alternative is to use Eclipse Java Compile EJC. It supports in-memory compilation and you can get your java code turned into byte code without creating any files on the disk.
The most nerdish solution would be to alter the byte code of your class and then reload it into your own JDK using debug mode. I will not recommend to actually to it. You can get more information on this approach exploring source code of the popular mocking library JMockit.
Upvotes: 2
Reputation: 3347
Your task is impossible.
You can't add any field into the class in runtime by your code.
Instead of this request you have to change your solution to something what will take your Tiles.
That can be almost any type of collection. You have to analyze what is the best usage and decide what to further use.
Best luck.
Upvotes: 2
Reputation: 4623
You cannot alter the definition of a class at runtime, programatically. E.g. you can't add static fields.
You need to use a collection. Like you said, ArrayList
is one of the many options.
Upvotes: 2