反射
来源:互联网 发布:苏新诗毛糙体简 mac 编辑:程序博客网 时间:2024/06/14 20:38
public class Text { /** * @param args * @throws ClassNotFoundException * @throws SecurityException * @throws NoSuchMethodException */ public static void main(String[] args) throws Exception { // TODO Auto-generated method stub /* * 三种方式的反射: */// 第一种// Class<?> forName = Class.forName("com.libin.text.Person"); Person person = new Person();// 第二种// Class<? extends Person> class1 = person.getClass();// 第三种 Class<Person> class2=Person.class;// 调用person的方法,第一个参数,是要查找的方法;第二个参数是该方法的参数类型// 当我把setname方法设置成私有的时候,就不可以使用了// Method method = class2.getMethod("setName", String.class);// 获取私有方法 Method method = class2.getDeclaredMethod("setName", String.class);// 设置暴力反射 method.setAccessible(true);// 执行反射的方法 method.invoke(person, "李彬"); Method method2 = class2.getDeclaredMethod("getName", null); method2.setAccessible(true); String name=(String) method2.invoke(person, null); System.out.println(name); }}
Person
package com.libin.text;public class Person { private String name; private String sex; private int age; public Person(String name, String sex, int age) { super(); this.name = name; this.sex = sex; this.age = age; } public Person() { super(); // TODO Auto-generated constructor stub } private String getName() { return name; } private void setName(String name) { this.name = name; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public int getAge() { return age; } public void setAge(int age) { this.age = age; }}
0 0
- 反射
- 反射
- 反射
- 反射
- 反射
- 反射
- 反射
- 反射
- 反射
- 反射
- 反射
- 反射
- 反射
- 反射
- 反射
- 反射
- 反射
- 反射
- C++ 操作cmd并返回结果
- ti L138 board
- 检测使用 three.js 时的 WebGL 和浏览器兼容性(Detecting WebGL and browser compatibility with three.js)(转)
- Activity的生命周期和启动模式-Android开发艺术探索读书笔记第一章
- 关于slax
- 反射
- java实现无组件导出CSV文件
- Eclipse ANT
- 使用LayoutParams设置布局
- Adobe AIR 代码签名证书使用指南
- 【C语言】数组与指针
- 苹果Mac系统开发必备资源
- PYthon投票程序段以及sorted函数说明
- MySQL 索引的创建、删除和查看操作