从调用方法获得本地变量的值而不返回
在Java中,调用方法是否可以在调用的方法内获取局部变量的值而不返回它?从调用方法获得本地变量的值而不返回
请看下面的C,我可以用指针来改变乐趣函数的局部变量的值。
#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);
}
}
“你可以传入一个集合的引用”。或者我可以传入Array或ArrayList
您可以使用方法作为您的全局变量的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
}
}
感谢您的回应。 a)它不编译,int g = 10;声明应该在main之前,并且应该是static int g = 10; b)正如我在原文中提到的,我希望变量是本地的。 – saltandwater
我刚编辑你的代码。试图解释java中没有指针。所以你应该做这样的事情。 –
Java没有指针。如果这是可能的,那就意味着“局部变量”不是局部的,这是矛盾的。 – Aganju