[英]How do I call a non-static method from another class in a non-static method? (java)
[英]Java, pass non-static method into another method
这是我的程序的设置。 我想从method1或method2告诉方法checkerMethod使用哪个方法。
public Class executeCode{
World brave = new World();
brave.checkerMethod(Method method1);
}
我的世界水平看起来像下面的样子。
public World{ // changed to World from World()
public World(){
//make world
}
public methodChecker(Method method){
//code involving using method1 or method2
//methods 1 and 2 are not static, so I would need to call this.method1()
}
public void method1(){//method here}
public void method2(){//method here}
}
我在这里看到了类似的东西
上面的解决方案显然不适用于通过非静态方法。
我有一种感觉,如果我重新安排事情可能会奏效,但我无法弄清楚。 任何帮助,将不胜感激!
而不是传递方法并进行反射式处理,只需传递一个包装了该方法并关闭this
方法的可调用对象。
如果要传递的所有方法都是void
零参数方法,则可以只使用java.lang.Runnable
// final local variables are available to inner classes
final World current = this;
World.methodChecker(
new Runnable() {
public void run() {
current.method1();
// Or alternatively {World.this.method1();}
}
});
如果您需要实际返回值或传递参数,那么Guava的Function
并不是一个不错的选择。
您无法在Java中(没有反射)执行此操作,但是可以使用标志来标记要执行的确切方法:
public void methodChecker(boolean flag){
flag ? method1() : method2();
}
正确的做法是考虑重新设计和制作methodN()
Runnable
的,而不是方法。
public class World {
public Runnable method1 = new Runnable() {
@Override
public void run() {
System.out.println("1");
}
};
public Runnable method2 = new Runnable() {
@Override
public void run() {
System.out.println("2");
}
};
public World() {
//make world
}
public void methodChecker(Runnable method) {
method.run();
}
}
当然可以将methodN()
保留为方法并使用反射运行它们。 这不是一个好习惯,调用速度较慢,并且您有在其他环境中面临SecurityException
风险。 除非别无选择,否则不要使用反射。 解决方法如下:
public class World {
public World() {
//make world
}
public void methodChecker(String method) {
try {
getClass().getMethod(method).invoke(this);
} catch (Exception ex) {
ex.printStackTrace();
}
}
public void method1() {
System.out.println("1");
}
public void method2() {
System.out.println("2");
}
}
静态方法调用的唯一区别是您将对对象的引用传递给invoke
方法。 在例如使用Runable
没有任何区别。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.