首页 > 解决方案 > Java 在转换为 Object 后更改变量的值

问题描述

我试图在将变量转换为对象后更改它。这在 Java 中是否可行,或者是否有其他选项可以做类似的事情?

Double a = 1.;
Object o = a;
Double b = (Double)o;
b = 2.;
System.out.println(a); // print 2

标签: java

解决方案


如果有两个引用指向同一个对象,则不能更改两个引用中的一个,如果它们分配给一个新对象。

Double a = 1.,
Double b = a;
Double b = 2.; // here b now points to new object. a is not changed. Now you have two separate variables pointing to separate objects.

如果你真的需要,那么你需要使用具有 setter/better 的包装类来操纵内部状态

DoubleWrapper a = new DoubleWrapper(2); // not a standard JDK class. You will need to write it yourself
DoubleWrapper b = a;
b.set(1);
System.out.println(b.get()); // prints 1
System.out.println(a.get()); // also prints 1

推荐阅读