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()); } }
The java.lang.IllegalArgumentException: object is not an instance of declaring class error occurred during programming. The reason for the error is that the first parameter of the invoke method is the instantiated object of the class to which the reflected method belongs, here is student