Decided to open an article to record the bits and pieces of knowledge

1: An example about reflection2018/3/10 3:0:29
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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326279938&siteId=291194637