`
粟谷_sugu
  • 浏览: 25375 次
社区版块
存档分类
最新评论

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

阅读更多
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
分享到:
评论
1 楼 ZJKAICO 2018-03-21  
 

相关推荐

Global site tag (gtag.js) - Google Analytics