class Student{ int id; String name; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } } public class reflectTest { public static void main(String[] args) { Student student = new Student(); Method method = null; try { method = student.getClass().getMethod("setName", String.class); method.invoke(student,"abc"); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } System.out.println(test.getName()); } }
编程时出现过java.lang.IllegalArgumentException: object is not an instance of declaring class错误,错误原因是invoke方法的第一个参数要是被反射方法所属类的实例化对象,此处为student