简体   繁体   English

Field.get() 返回 'null'

[英]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我尝试使用注释来注册功能的设置,但我无法反映设置字段,我做错了什么,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);但是当我使用Setting setting = (Setting) field.get(this); , it actually will be set to 'null' , 它实际上将被设置为 'null'

the Feature child:特色孩子:

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

BoolenSetting is Setting child BoolenSetting 是设置孩子

this is the annotation这是注释

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

Subclass field initialisers are run after the superclass constructor, so this is to be expected.子类字段初始化程序在超类构造函数之后运行,因此这是可以预料的。 See also Java initialisation order .另见Java 初始化命令

When the Feature constructor is run, the annotated fields have not been initialised yet, so they are all null.运行Feature构造函数时,注解字段还没有初始化,所以都是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.修复它的一个简单方法是要求子类在它们自己的构造函数中调用类似registerSettings的东西,此时,所有子类的字段都将被初始化。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM