反射机制——获取Class中的字段

一、demo1

/** 
* @Title: ReflectDemo3.java 
* @Package com.lh.reflection 
* @Description: TODO
* @author Liu 
* @date 2018年1月23日 下午6:05:34 
* @version V1.0 
*/
package com.lh.reflection;

import java.lang.reflect.Field;

import com.lh.reflection.bean.Person;

/** 
* @ClassName: ReflectDemo3 
* @Description: 获取Class中的字段
* @author Liu
* @date 2018年1月23日 下午6:05:34 
*  
*/
public class ReflectDemo3 {

	/**
	 * @throws Exception *
	* @Title: main 
	* @Description: TODO
	* @param @param args
	* @return void
	* @throws 
	*/
	public static void main(String[] args) throws Exception {
		getFieldDemo();
	}

	/**
	 * @throws Exception *
	* @Title: getFieldDemo 
	* @Description: TODO
	* @param 
	* @return void
	* @throws 
	*/
	private static void getFieldDemo() throws Exception {
		String name = "com.lh.reflection.bean.Person";

		// 寻找该类名称字节码文件 ,并加载至内存,生成Class对象
		Class<Person> clazz = (Class<Person>) Class.forName(name);
		
		Field field = null; //clazz.getField("age");//只能获取公有的
		
		field = clazz.getDeclaredField("age");//只获取本类,但包含私有
		
		//对私有字段的访问取消权限检查,暴力访问,应避免!
		field.setAccessible(true);
		
		Person person = clazz.newInstance();
		
		field.set(person, 20);
		Object obj = field.get(person);
		
		System.out.println(obj);
	}
	
	

}

二、demo2

    ReflectPoint.java

package staticimport.reflect;

public class ReflectPoint {
	private int x;
	public int y;
	
	private String type = "bball";
	
	private String edu = "itcast";
	
	private String pe = "basketball";
	
	public ReflectPoint(){}
	
	public ReflectPoint(int x, int y) {
		this.x = x;
		this.y = y;
	}

	@Override
	public String toString() {
		return "ReflectPoint [x=" + x + ", y=" + y + ", type=" + type + ", edu=" + edu + ", pe=" + pe + "]";
	}

}
package staticimport.reflect;

import java.lang.reflect.Field;

public class ReflectFieldTest {

	public static void main(String[] args) throws Exception {
		ReflectPoint reflectPoint = new ReflectPoint(4, 5);
		
		Field fieldY = reflectPoint.getClass().getField("y"); 
		System.out.println(fieldY.get(reflectPoint));
		
		//不可见
//		Field fieldX = reflectPoint.getClass().getField("x");
		//获取本类已声明的字段(包含私有)
		Field fieldX = reflectPoint.getClass().getDeclaredField("x");
		
		//设置可强制访问
		fieldX.setAccessible(true);
		
		fieldX.set(reflectPoint, 10);
		
		//访问
		System.out.println(fieldX.get(reflectPoint));
	}

}

 

转载于:https://my.oschina.net/Howard2016/blog/1611990

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值