这是一个简单的工作示例,显示了使用reflection可以执行的一些操作。
注意:我决定在列表中存储可用的方法,但是可以很容易地修改它以使用预定义的字符串列表。我还从worker方法中抛出了一个未经检查的IllegalArgumentException。
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class Worker {
public void method1() {
System.out.println("method1 called");
}
public void method2() {
System.out.println("method2 called");
}
public void worker(String handle) throws IllegalArgumentException {
Class extends Worker> clazz = this.getClass();
List methods = Arrays.asList(clazz.getMethods());
if (methods.stream().map(m -> m.getName()).collect(Collectors.toList()).contains(handle)) {
try {
Method method = clazz.getDeclaredMethod(handle);
method.invoke(this);
} catch (InvocationTargetException | NoSuchMethodException | IllegalAccessException e) {
e.printStackTrace();
}
} else {
throw new IllegalArgumentException("Don't understand ");
}
}
public static void main(String[] args) {
new Worker().worker("method1");
new Worker().worker("method2");
new Worker().worker("method3");
}
}