java.lang.NoSuchMethodException: com.gen.entity.User.sayHi()private void com.gen.entity.User.sayHi(java.lang.String)
at java.lang.Class.getDeclaredMethod(Class.java:2130)
at com.gen.test.TestRefelect1.demo01(TestRefelect1.java:27)
at com.gen.test.TestRefelect1.main(TestRefelect1.java:12)
我的代码是这样的:
package com.gen.test;
import java.io.FileInputStream;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Properties;
public class TestRefelect1 {
public static void main(String[] args) {
demo01();
}
static void demo01() {
Properties properties = new Properties();
String name = "D:\\eclipse-workspace\\WEB\\javaPromote\\src\\com\\gen\\test\\class.txt";
try {
properties.load(new FileInputStream(name));
String classname = properties.getProperty("classname");
String methodname = properties.getProperty("methodname");
Class<?> forName = Class.forName(classname);
Method[] declaredMethods = forName.getDeclaredMethods();
for (Method method : declaredMethods) {
System.out.println(method);
}
Method method = forName.getDeclaredMethod(methodname);
System.out.println(method);
method.setAccessible(true);
method.invoke(forName, "lisi");
} catch (IOException | ClassNotFoundException | SecurityException
| IllegalArgumentException | NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
错误
所有的方法可以遍历出来,但是调用特定的方法却不可以
改正
package com.gen.test;
import java.io.FileInputStream;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Properties;
public class TestRefelect1 {
public static void main(String[] args) {
demo01();
}
static void demo01() {
Properties properties = new Properties();
String name = "D:\\eclipse-workspace\\WEB\\javaPromote\\src\\com\\gen\\test\\class.txt";
try {
properties.load(new FileInputStream(name));
String classname = properties.getProperty("classname");
String methodname = properties.getProperty("methodname");
Class<?> forName = Class.forName(classname);
Method[] declaredMethods = forName.getDeclaredMethods();
for (Method method : declaredMethods) {
System.out.println(method);
}
Method method = forName.getDeclaredMethod(methodname,String.class);
System.out.println(method);
method.setAccessible(true);
method.invoke(forName, "lisi");
} catch (IOException | ClassNotFoundException | SecurityException
| IllegalArgumentException | NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
主要在27行改正了
Method method = forName.getDeclaredMethod(methodname,String.class);
结果
需要注意的地方
Method Class.getDeclaredMethod(String name, Class<?>... parameterTypes)
的作用是获得对象的所有方法
该方法的第一个参数name是要获得方法的名字,第二个参数parameterTypes是按声明顺序标识该方法形参类型,一定要写上(部分教程说这个参数可以省略)。