我有 A1.java, A2.java, A3.java ... A10.java 等十个类(也许更多);
他们里面都有一个public static String getResponse()
的方法,不过里面所做的事情和回复的字符串都不一样;
我还有一个变量 String name = "A1";
,不确定变量里面的到底是哪一个类的名字,不过肯定是这是个类里面的一个。
我想当我收到这个name变量之后动态调用所对应的类的get
Response方法,而且不想用if-else一个个判断。
试了下下面的代码,forName回复的是一个class对象,好像不能强制类型转换。能转换也不知道到底转换成哪一个对象,我不想一个个if-else判断。
String result = Class.forName(name).getResponse();
PHP中文网2017-04-18 10:57:19
This is the use of Java reflection.
First you need to get the specified method object (Method) through the Class.forName
获取一个类的 Class 对象, 然后通过这个 Class 对象的 getMethod
method, and finally call this method through this Method object.
Represented in source code:
public class Test {
public static String getResponse() {
return "This is Test.getResponse";
}
public static void main(String[] args) throws Exception {
String name = "com.test.Test";
String methodName = "getResponse";
Class<?> threadClazz = Class.forName(name);
Method method = threadClazz.getDeclaredMethod(methodName);
System.out.println(method.invoke(null));
}
}
天蓬老师2017-04-18 10:57:19
class.forName gets the class object. Then you can get the corresponding method through the getMethod method of this class object. Then invoke the corresponding method
天蓬老师2017-04-18 10:57:19
Can all these 10 classes implement an interface, such as
public interface A0 {
public String getResponse();
}
Then A1, A2... are all implements A0
,并实现getResponse
(but they cannot be defined as static).
Then you can write like this:
String result = ((A0) Class.forName(name).newInstance()).getResponse();
PHPz2017-04-18 10:57:19
In addition to reflection, you can also use Spring. Use the obtained string to get a bean, and then call the method.