从被调用的方法获取局部变量的值而不返回

时间:2016-07-02 19:18:25

标签: java c pointers local-variables

在Java中,调用方法是否可以在调用方法中获取局部变量的值而不返回它?

请参阅下面的C,我可以使用指针来更改 fun 函数的局部变量的值。

#include <stdio.h>

int main(void) {

    int* a;
    a = malloc(sizeof(int));
    *a = 10;

    printf("before calling, value == %d\n",*a);
    fun(a);
    printf("after calling, value == %d",*a);

    return 0;
}

int fun(int* myInt)
{
    *myInt = 100;
}

我可以在Java中做类似的事情。我确实尝试了,但是没能。

public class InMemory {

    public static void main(String[] args) {
        int a = 10;

        System.out.println("before calling ..."+a);
        fun(a);
        System.out.println("after calling ..."+a);
    }

    static void fun(int newa)
    {
        newa = 100;
    }
}

2 个答案:

答案 0 :(得分:0)

int和Integer不可变。您可以传入对集合的引用并修改它的内容,或者如果您热衷于它,则使用整数的可变实现,例如AtomicInteger。

public class InMemory {
    public static void main(String[] args) {
        AtomicInteger a = new AtomicInteger(10);

        System.out.println("before calling ..." + a);
        fun(a);
        System.out.println("after calling ..." + a);
    }

    static void fun(AtomicInteger newa) {
        newa.set(100);
    }
}

答案 1 :(得分:0)

您可以使用方法作为全局变量的setter来获取该函数的局部变量。

public class InMemory {

static int g=10;  // global in class

    public static void main(String[] args) {

    System.out.println("before calling ..."+g);
    fun();
    System.out.println("after calling ..."+g);
    }

    static void fun()
    {
    int l = 100; // local in fun
g = l; // assign value to global 
    }
}