gpt4 book ai didi

java - 使用当前类中的变量运行不同类中的方法

转载 作者:行者123 更新时间:2023-12-01 20:57:10 25 4
gpt4 key购买 nike

我需要运行不同类中的方法,但我想使用我要调用该方法的类中的方法的变量。我不想传递参数,因为该方法有太多变量,而且它会破坏我原始类的代码。

我的代码示例如下 -

运行方法的类

variable1;
variable2;
variable3;
otherClass OC = new OtherClass();
otherClass.method();

所谓的“otherClass”方法(具有该方法的类)例如

variable1;
variable2;
variable3;
public void method()
{
//DOES STUFF WITH variable1 variable2 and variable3
}

我想要它做的是使用我调用该方法的类中的变量运行该方法,即我首先发布的代码的类。有什么办法可以做到这一点吗?

最佳答案

正如 OldProgrammer 所说,正确的解决方案是使用容器来封装方法所需的所有变量。

一个例子:

public class ContainerClassExample {

private static class Container {
Object variable1, variable2, variable3;

public Container(Object variable1, Object variable2, Object variable3) {
this.variable1 = variable1;
this.variable2 = variable2;
this.variable3 = variable3;
}
}

public static void main(String[] argv) {
Container aContainer = new Container("a", "b", "c");
methodA(aContainer);
System.exit(0);
}

public static void methodA(Container input) {
// Do something with variable1, variable2, and variable3
}
}

输入参数个数越大,建议使用 builder pattern创建您的容器。

关于java - 使用当前类中的变量运行不同类中的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42163459/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com