soo recently i started minecraft modding and i came up with idea to make code cleaner a bit, i made some mods for other games, but they were in lua (Forts especially)
I wanted to ask if there is option to call sub-class using [] or smth else, here is example of what i want to achieve
ModItems.rock.get(); // current state
i want to replace .rock with something like:
ModItems[itemName].get();
is there any way to do that?
i tried searching everywhere but i couldn’t find anything or how to name it, if there’s any simple solution please show it
>Solution :
accessing members of a class using bracket notation like ModItems[itemName].get() is not directly supported because Java does not support bracket notation for field access in the same way that languages like JavaScript do. However, you can achieve a similar effect using a Map or by implementing a method that handles this logic.
-
Here’s how you can achieve this using a Map:
import java.util.HashMap; import java.util.Map; public class ModItems { private static final Map<String, Item> items = new HashMap<>(); static { items.put("rock", new Item("rock")); items.put("stone", new Item("stone")); // Add other items as needed } public static Item getItemByName(String name) { return items.get(name); } } -
Define your Item class:
public class Item { private String name; public Item(String name) { this.name = name; } public void get() { System.out.println("Getting item: " + name); } } -
Access the items using the new method:
public class Main { public static void main(String[] args) { String itemName = "rock"; ModItems.getItemByName(itemName).get(); } }
This approach allows you to dynamically access items based on a string key, similar to using bracket notation in other languages.