一、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));
}
}