dimanche 26 janvier 2020

Java reflection - Get a class variable by passing the name

I have a class (it's a Singleton in my project) with some variables. I would like to get one of those variable by passing its name in a function. For now i have :

public final class Configuration {
   private static volatile Configuration instance = null;
   //Here usual code to instanciate singleton

   String var1;
   int var2;
   boolean var3;

   public static Object Get(String varname)throws IllegalArgumentException, IllegalAccessException {
       for(Field field : instance.getClass().getFields())
            if(field.getName() == varname) 
                return field.get(field);
       return null;
   }

}

From the debugger i know that instance.getClass().getFields() return an empty Field[], but i do not understand why.





Aucun commentaire:

Enregistrer un commentaire