欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

决定开一篇文章专门记录零零碎碎的知识点  

程序员文章站 2024-02-02 09:38:40
...
1:关于反射的例子 2018/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());
    }

}

编程时出现过java.lang.IllegalArgumentException: object is not an instance of declaring class错误,错误原因是invoke方法的第一个参数要是被反射方法所属类的实例化对象,此处为student