Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is there any alternative to dot while calling sub-classes

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

  1. 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);
        }
    }
    
  2. 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);
        }
    }
    
  3. 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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading