java反射的实例

本文介绍Java反射机制的应用实例,包括如何获取私有成员变量的值、修改字符串类型的变量值及遍历对象中所有字符串类型的属性。
package com.juziku;

/**
* 反射类
* @author sunlightcs
* 2011-3-5
* http://hi.juziku.com/sunlightcs/
*/
public class ReflectPoint {
/**
* 私有变量x
*/
private int x;

public int y;
public String str1 = "abc";
public String str2 = "123";

public ReflectPoint(int x, int y) {
super();
this.x = x;
this.y = y;
}

}

package com.juziku;

import java.lang.reflect.Field;

/**
* 反射例子
* @author sunlightcs
* 2011-3-5
* http://hi.juziku.com/sunlightcs/
*/
public class ReflectTest {

public static void main(String[] args) throws Exception{

ReflectPoint reflectPoint = new ReflectPoint(3,5);

/**
* 通过反射,获得ReflectPoint属性的值
*
* reflectPoint.getClass()表示获得ReflectPoint的字节码,
* 当然也可以写成Field fieldY = ReflectPoint.class
* 或Class.forName("com.juziku.ReflectPoint");
* 获得某个类的字节码的方法有3种:
* ReflectPoint.class (类名.class)
* reflectPoint.getClass() (对象名.getClass())
* Class.forName("com.juziku.ReflectPoint") (Class.forName(类名的路径))
*
* reflectPoint.getClass().getField("y")表示获得ReflectPoint里y属性的位置
*/
Field fieldY = reflectPoint.getClass().getField("y");

/**
* fieldY.get(reflectPoint)表示获得reflectPoint对象里,y位置对应属性的值
*/
Object y = (Object)fieldY.get(reflectPoint);

/**
* 打印reflectPoint对象里,属于为y的值
*/
System.out.println(y);



/**
* 获得x属性的值,由于x属于为private类型,
* 所以要通过getDeclaredField方法查询x所在的位置
*/
Field fieldX = reflectPoint.getClass().getDeclaredField("x");

/**
* 由于x属于为private类型,也要设置成可访问,不然获取不到值
*/
fieldX.setAccessible(true);
Object x = (Object)fieldX.get(reflectPoint);
System.out.println(x);


/**
* 获得类型为String的所有值
*/
getStringValues(reflectPoint);


/**
* 修改str1属性的值
*/
onchageValue(reflectPoint);

}

private static void getStringValues(Object obj) throws Exception{
/**
* 获得所有属性的位置
*/
Field[] fields = obj.getClass().getFields();

for(Field field : fields){
/**
* 这里建议用==,不建议用equals
* 如果field属性是String类型的话,那么跟String的字节码是同一份
*/
if(field.getType() == String.class){
String str = (String)field.get(obj);
System.out.println(str);
}
}
}

private static void onchageValue(Object obj) throws Exception{
Field field = obj.getClass().getField("str1");
System.out.println(field.get(obj));
field.set(obj, "22");
System.out.println(field.get(obj));
}

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值