java 反射机制

 

反射 是jdk1.2的特性:反射就是把java类中的各种成分映射成一个个的java对象

获取class的三种方法: 类的对象.getClass() ;  类.class ;  Class.forName("类路径");

public class RefiectPoint {
	
	private int x;
	public int y;
	public String str1 = "ball"; 
	public String str2 = "basktball"; 
	public String str3 = "itcast";
	public RefiectPoint(int x, int y) {
		super();
		this.x = x;
		this.y = y;
	}
	@Override
	public String toString() {
		return "RefiectPoint [x=" + x + ", y=" + y + ", str1=" + str1 + ", str2=" + str2 + ", str3=" + str3 + "]";
	}
	
}
public class RefiectTest {

	public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchFieldException {
		String str1 = "abc";
		Class cls1 = str1.getClass();
		Class cls2 = String.class;
		Class cls3 = Class.forName("java.lang.String");
		System.out.println(cls1 == cls2);
		System.out.println(cls1 == cls3);
		System.out.println(cls1.isPrimitive()); // 是否是原始类型
		System.out.println(int.class.isPrimitive());
		System.out.println(int.class == Integer.class);
		System.out.println(int.class == Integer.TYPE); //type:表示包装类对应的基本类型
		System.out.println(int[].class.isPrimitive()); 
		System.out.println(int[].class.isArray());  // 数组类型的class实例对象 Class.isArray()
		// 只要是在源程序中出现的类型, 都有各自的Class实例对象
		
		// new String(new StringBuffer("abc"));
		Constructor<String> constructor1 = String.class.getConstructor(StringBuffer.class);
		String str2 = constructor1.newInstance(new StringBuffer("abc"));
		System.out.println(str2);
		System.out.println(str2.charAt(2));
		
		RefiectPoint pt1 = new RefiectPoint(3, 5);
		Field fieldy = pt1.getClass().getField("y");
		System.out.println(fieldy.get(pt1));
		Field fieldx = pt1.getClass().getDeclaredField("x"); // 私有的属性
		fieldx.setAccessible(true); // 暴力反射
		System.out.println(fieldx.get(pt1));
		
		changeStringValue(pt1);
		System.out.println(pt1);
	}

	private static void changeStringValue(Object obj) throws IllegalArgumentException, IllegalAccessException {
		Field[] fields = obj.getClass().getFields();
		for( Field field : fields ) {
			//if(field.getType().equals(String.class)) {
			if(field.getType() == String.class) { // 这里应当用 双等号  应为只有一个字节码文件
				String oldValue = (String) field.get(obj);
				String newValue = oldValue.replace('b', 'a');
				field.set(obj, newValue);
			}
		}
		
	}

}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值