Home > Net >  Field.get() return 'null'
Field.get() return 'null'

Time:01-03

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'

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();
}

CodePudding user response:

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();
    // ...
}
  •  Tags:  
  • java
  • Related