Java反射技术的简单使用
Java反射技术的简单使用
实例:
一个普通了类:给定了string对象的值,下面利用反射技术要将name的值换成ddd
- public class haha {
- public String name = "bbb";
- public String sex = "dddd";
- public String getName() {
- return name;
- }
- }
测试类:
- import java.lang.reflect.Constructor;
- import java.lang.reflect.Field;
- import java.lang.reflect.InvocationTargetException;
- public class tt {
- public static void main(String[] args) throws IllegalArgumentException,
- IllegalAccessException, ClassNotFoundException, SecurityException,
- NoSuchMethodException, InstantiationException,
- InvocationTargetException {
- // 获得一个String类型String(StringBuffer stringbuffer)构造方法对象
- Constructor constructor = String.class
- .getConstructor(StringBuffer.class);
- // 根据constructor对象构建一个新的字符串对象
- String strs = (String) constructor
- .newInstance(new StringBuffer("jjjjj"));
- System.out.println("利用反射技术new了一个字符串:" + strs);
- try {
- haha h = new haha();
- System.out.println("反射操作前的值是:" + h.name);
- // 得到haha类字节码
- Class hh = Class.forName("test.haha");
- // 得到name属性的对象
- Field filed = hh.getField("name");
- // 根据对象获得具体对象(h)中的name属性值
- String value = (String) filed.get(h);
- String newvalue = value.replace("b", "d");
- // 为name属性设置新的值
- filed.set(h, newvalue);
- System.out.println("反射操作后的值是" + h.name);
- } catch (SecurityException e) {
- e.printStackTrace();
- } catch (NoSuchFieldException e) {
- e.printStackTrace();
- }
- }
- }
评论暂时关闭