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

Field.get() return 'null'

i try to use annotation to register settings for a Feature, but i cant reflect the setting field, what i did wrong, ty

this is Feature init, i want add settings

public Feature() {
    try {
        Class<SettingAnno> anno = SettingAnno.class;
        for (Field field : this.getClass().getDeclaredFields()) {
            if (field.isAnnotationPresent(anno)) {
                Setting setting = (Setting) field.get(this);
                this.settings.add(setting);
            }
        }
    }
    catch (Exception e) {
        e.printStackTrace();
    }
}

but when i use Setting setting = (Setting) field.get(this);, it actually will be set to ‘null’

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

the Feature child:

public final class FeatureChild extends Feature {
    @SettingAnno("setting1")
    public final BooleanSetting setting1 = new BooleanSetting(true);
}

BoolenSetting is Setting child

this is the annotation

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface SettingAnno {
    String value();
}

>Solution :

Subclass field initialisers are run after the superclass constructor, so this is to be expected. See also Java initialisation order.

When the Feature constructor is run, the annotated fields have not been initialised yet, so they are all null.

An easy way to fix it would be to require subclasses to call something like a registerSettings in their own constructor, at which point, all the subclass’ fields would have been initialise.

// in Feature...
public final void registerSettings() {
    try {
        Class<SettingAnno> anno = SettingAnno.class;
        for (Field field : this.getClass().getDeclaredFields()) {
            if (field.isAnnotationPresent(anno)) {
                Setting setting = (Setting) field.get(this);
                this.settings.add(setting);
            }
        }
    }
    catch (Exception e) {
        e.printStackTrace();
    }
}
// in FeatureChild...

public FeatureChild() {
    registerSettings();
    // ...
}
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