列表项的动态反射对象初始化不会更改原始对象

时间:2019-05-02 12:32:09

标签: java dynamic reflection initialization

我正在尝试使用java反射动态初始化列表的对象,但是这样做之后,原始对象仍保持原始值,并且原始对象与相应列表项之间的链接断开。

下面是一段代码,可以更好地理解我的问题:

public class TimeModule {
    int value;

    public TimeModule() {
        this.value = 1;
    }

    public void setValue(int value) {
        this.value = value;
    }

    public int getValue() {
        return this.value;
    }

    public String print() {
        return "value: " + this.value;
    }
}


public class TimeModuleExtended1 extends TimeModule {

    double foo;

    public TimeModuleExtended1() {
        super();
        this.foo = 1.0;
    }

    public void setFoo(double foo) {
        this.foo = foo;
    }

    public double getFoo() {
        return this.foo;
    }

    @Override
    public String print() {
        return "value: " + this.value + ", foo:" + this.foo; 
    }
}


public class TimeModuleExtended2 extends TimeModule {

    double bar;

    public TimeModuleExtended2() {
        super();
        this.bar = 1.0;
    }

    public void setBar(double bar) {
        this.bar = bar;
    }

    public double getBar() {
        return this.bar;
    }

    @Override
    public String print() {
        return "value: " + this.value + ", bar:" + this.bar; 
    }
}

这是主要代码:     导入java.util.ArrayList;     导入java.util.List;

public class Test {

    public static void main(String[] args) {
        TimeModuleExtended1 t1 = new TimeModuleExtended1();
        t1.setValue(2);
        t1.setFoo(2.0);
        System.out.println("Initial Values:");
        System.out.println(t1.print());

        TimeModuleExtended2 t2 = new TimeModuleExtended2();
        t2.setValue(3);
        t2.setBar(3.0);
        System.out.println(t2.print());

        List<TimeModule> modules = new ArrayList<>();
        modules.add(t1);
        modules.add(t2);

        // reinitialize Time Base modules
        for (int i = 0; i < modules.size(); i++) {
            TimeModule m = modules.get(i);
            try {
                modules.set(i, (TimeModule) m.getClass().getConstructors()[0].newInstance());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        System.out.println("\nList Values: ");
        for (int i = 0; i < modules.size(); i++) {
            System.out.println(modules.get(i).print());
        }

        System.out.println("\nObject Values: ");
        System.out.println(t1.print());
        System.out.println(t2.print());        
    }
}

输出看起来像这样:

Initial Values:
value: 2, foo:2.0
value: 3, bar:3.0

List Values: 
value: 1, foo:1.0
value: 1, bar:1.0

Object Values: 
value: 2, foo:2.0
value: 3, bar:3.0

如您所见,列表值不等于对象值;如何使它们具有相似的值?

0 个答案:

没有答案