jeudi 11 août 2016

Load a class attribute dynamically

I'd like to load a class attribute dynamically. For example:

String day = "java.time.DayOfWeek.FRIDAY";
int lastDot = 
Object o = function(day);
// o would contain DayOfWeek.FRIDAY

One solution would be to split the thing to get the class name and the attribute name, and then do relection :

Dirty solution:

    String day = "java.time.DayOfWeek.FRIDAY";
    int lastDot = day.lastIndexOf(".");
    String clazz = day.substring(0, lastDot);
    String field = day.substring(lastDot + 1);
    Object o = Class.forName(clazz).getDeclaredField(field).get(null);

I'm looking for a standard method that would encapsulate the substrings and relection code. The example is on an enum, but the solution should work for classes/interfaces.

Thanks





Aucun commentaire:

Enregistrer un commentaire