mercredi 4 août 2021

Best way to initialize class fields

what is the best way to initialize class fields when there are several needs with reflection? It is better to create an initialize method or put everything in the same constructor, below I have put 2 examples, which is the best way?

public House(String name) {
     this.name = name ;
     prices = new HashMap<>();
     initialize();
}

private void initialize() {
    try {
        Object func = Class.forName("network.game.engine.ExpansionsFunction").invoke(name);
        houseProfile = Main.GET_FUNCTION_METHOD.invoke(func);
        houseMap = Main.HOUSE_MAP_METHOD.invoke(houseProfile);
    } catch (IllegalAccessException | InvocationTargetException e) {
        throw new IllegalStateException(e.getCause());
    }
}

public House(String name) {
     this.name = name ;
     prices = new HashMap<>();
     try {
         Object func = Class.forName("network.game.engine.ExpansionsFunction").invoke(name);
         houseProfile = Main.GET_FUNCTION_METHOD.invoke(func);
         houseMap = Main.HOUSE_MAP_METHOD.invoke(houseProfile);
     } catch (IllegalAccessException | InvocationTargetException e) {
         throw new IllegalStateException(e.getCause());
     }
}




Aucun commentaire:

Enregistrer un commentaire