[英]How to call a method whose name is the value of a string variable in java?
[英]How to call a method by name (String) in Java?
类A<\/code>每个实例都有一个类
B<\/code>的实例。
A<\/code>应该根据其成员变量
method_num<\/code>在
B<\/code>调用不同的方法。这是一个实现我想要的实现:
public class A {
private B myB = new B();
public int method_num = 1;
public callBMethod() {
if ( method_num == 1 )
myB.method1();
else
myB.method2();
}
}
public class B {
public method1() { }
public method2() { }
}
如果您不想使用反射(这是一个很好的目标),那么enum
有一些简洁的功能可以让您将enum
设置为代理。
public class A {
private B myB = new B();
public int method_num = 1;
public void callBMethod() {
// Could do it by name.
BMethods.valueOf("method1").call(myB);
// Or by number.
BMethods.values()[method_num].call(myB);
}
}
enum BMethods{
method1 {
@Override
public void call(B b) {
b.method1();
}
},
method2 {
@Override
public void call(B b) {
b.method2();
}
};
public abstract void call (B b);
}
public class B {
public void method1() {
}
public void method2() {
}
}
你不能。 Java 不将函数视为第一类对象,因为它没有 Python 或 C# 之类的函数特性。
您可以创建一个 Command 接口并传递该对象引用:
public interface Command {
void execute(Object [] args);
}
我认为您可以像这样使用反射:
java.lang.reflect.Method method;
try {
method = obj.getClass().getMethod(methodName, param1.class, param2.class, ..);
} catch (SecurityException e) {
// ...
} catch (NoSuchMethodException e) {
// ...
}
try {
method.invoke(obj, arg1, arg2,...);
} catch (IllegalArgumentException e) { //do proper handling
} catch (IllegalAccessException e) {//do proper handling
} catch (InvocationTargetException e) {//do proper handling
也许与Runnable
对象? 您可以从 B 传递一个可运行文件,并直接从 A 调用.run()
Java 反射 API 为您提供了一种方法,可以将 Method 类型的对象与目标对象一起传递,然后可以在目标对象上调用该方法。
示例如下:
Method m; // The method to be invoked
Object target; // The object to invoke it on
Object[] args; // The arguments to pass to the method
// An empty array; used for methods with no arguments at all.
static final Object[] nullargs = new Object[] {};
/** This constructor creates a Command object for a no-arg method */
public Command(Object target, Method m) {
this(target, m, nullargs);
}
/**
* This constructor creates a Command object for a method that takes the
* specified array of arguments. Note that the parse() method provides
* another way to create a Command object
*/
public Command(Object target, Method m, Object[] args) {
this.target = target;
this.m = m;
this.args = args;
}
/**
* Invoke the Command by calling the method on its target, and passing the
* arguments. See also actionPerformed() which does not throw the checked
* exceptions that this method does.
*/
public void invoke() throws IllegalAccessException,
InvocationTargetException {
m.invoke(target, args); // Use reflection to invoke the method
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.