首先建一个实体类,用于数据访问
package star.july.entity;
public class Student {
private String name;
int age;
public String address;
public Student() {
super();
}
//私有构造方法
private Student(String name) {
super();
this.name = name;
}
public Student(String name, int age) {
super();
this.name = name;
this.age = age;
}
public Student(String name, int age, String address) {
super();
this.name = name;
this.age = age;
this.address = address;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
return "Student [name=" + name + ", age=" + age + ", address="
+ address + "]";
}
}
反射结果:
package star.july.dao;
import java.lang.annotation.Annotation;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
/**
* 反射:通过反射获取成员变量并使用
* @author Starjuly
*
*/
public class PrivateField {
public static void main(String[] args) throws Exception {
//获取字节码文件
Class clazz = Class.forName("star.july.entity.Student");
// Constructor con = clazz.getConstructor(); //获取公共的构造方法
Constructor con = clazz.getDeclaredConstructor(); //获取所有的构造方法
//创建实例
Object obj = con.newInstance();
//获取数据类型:公有的
Field addressField = clazz.getField("address");
//给该对象的数据类型赋值
addressField.set(obj, "广州");
System.out.println(obj);
//对私有的数据类型进行获取
Field nameField = clazz.getDeclaredField("name");
//要进行暴力反射才能访问私有类型
nameField.setAccessible(true);
//赋值
nameField.set(obj, "徐凤年");
System.out.println(obj);
}
}