在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;
}
}
最佳答案
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);
}
}
关于java - 从被调用方法中获取局部变量的值而不返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38163665/