mercredi 16 octobre 2019

Get field initialization value

I'm parsing class definitions through introspection and would like to know whether the class has explicitly defined a default value for some of its fields.

class Foo {
    private int member = 5; // Init value is 5
}

vs.

class Foo {
    private int member; // Default value is 0 but no init value defined
}

I could instanciate the class and get its members, but I wouldn't be able to distinguish between explicitly-initialized fields like private int member = 0; from implicitly-initialized like private int member; (which initial value is also 0, except that it was not explicitly set).

I'm using introspection through getDeclaredFields() which means I can't assume a specific type for the field, so I can't use an annotation like:

@DefaultValue(5)
private int member;

Because:

public @interface DefaultValue {
    Object value() default null; // Error "... only primitive type, String, Class, annotation, enumeration are permitted or 1-dimensional arrays thereof"
}

I was thinking about using a String in such annotation (instead of the Object I wanted to use) then code some deserialize() method to parse the string and retrieve the value, but it seems like an overkill (if there are nicer ways) and cannot be checked at compile time (e.g. @DefaultValue("toto") private int member; would compile but is broken).





Aucun commentaire:

Enregistrer un commentaire