我在方法A
中有一个字符串数组(变量),它存在于类A
中。现在我想访问它并使用 B 类
中的 方法 B
中的另一个字符串数组设置它。 B 类
位于A 类
中。
我是 Java 初学者,因此非常感谢任何帮助。非常感谢。
public class A {
B myclassb;
void methodA() {
String[] myvar;
}
}
public class B {
void methodB() {
// how do I get to A.methodA.myvar?
}
}
最佳答案
尚不完全清楚您想要实现什么,但无论如何我都会尝试回答。 选项 1:您说过要在嵌套类中的方法 b 中的方法 a 中分配一个变量。这是不可能直接实现的,因为函数变量无法从另一个函数访问,并且在函数完成执行后不再存在。所以你可以将它作为输入参数传输:
public class A {
public void a(String[] input){
String[] theArray = input;
}
private class B{
private void b(){
String[] input = new String[] {"an", "awesome", "Test"};
a(input);
}
}
}
选项 2:使用成员变量:
public class A {
private String[] theArray;
public void a(){
this.theArray = new String[] {"a", "nice", "Test"};
B bObject = new B();
//modify value within b():
bObject.b();
//or assign it using a return value:
this.theArray = bObject.b2();
}
private class B{
private void b(){
theArray = new String[] {"an", "awesome", "Test"};
}
private String[] b2(){
return new String[] {"an", "awesome", "Test"};
}
}
}
关于Java在方法中访问字符串数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31732962/