存储对象的引用

Xte*_*ter 1 java

我想在某个类中存储对变量的引用,并在此类中对其进行操作.操作应该修改原始变量.特别是下面的代码应该打印1而不是0.

class Test {
    private Long metric;

    public Test(Long m) {
        this.metric = m;
        ++this.metric;
    }
}

class Ideone
{
    public static void main (String[] args) throws java.lang.Exception
    {
        Long metric = 0L;
        Test test = new Test(metric);
        System.out.println(metric);
    }
}
Run Code Online (Sandbox Code Playgroud)

如何实现这种行为?

Kay*_*man 5

您可以替换Long使用AtomicLong这是可变的.但是你会丢失自动装箱功能.