我想做的是:
public class UIController {
UIController() {
//Call a method in MainClass here, for example MethodIWantToCall()
}
public void MethodA {
//Call a method in MainClass here, for example MethodIWantToCall()
}
}
UIController类示例:
$Data::Dumper::Indent
我想要做的是UIController传递给MainClass命令,调用其方法或在用户与UI交互时将值返回给MainClass。
答案 0 :(得分:2)
您需要将MainClass
实例的引用传递给UIController
实例,例如:
public class UIController {
private final MainClass mainClass;
UIController (final MainClass mainClass) {
this.mainClass = mainClass;
//Call a method in MainClass here, for example MethodIWantToCall()
this.mainClass.MethodIWantToCall();
}
public void MethodA() {
//Call a method in MainClass here, for example MethodIWantToCall()
this.mainClass.MethodIWantToCall();
}
}
然后
uIController = new UIController(this);
PS:Java中的方法应该从小写开始。
答案 1 :(得分:-1)
您可以创建实例字段:
public class MainClass {
public static MainClass instance;
public MainClass() {
instance=this;
}
public void method() {}
}
然后,调用:MainClass.instance.method();或者:
public class MainClass {
public MainClass() {
new AnotherClass(this);
}
public void method() {}
}
public class AnotherClass {
public AnotherClass(MainClass main) {
main.method();
}
}