JavaSE 反射——访问对象属性

Java自我学习路线

访问对象属性

  • 给属性赋值,使用set方法
  • 获取属性值,使用get方法
  • 私有属性无法直接访问,需要打破封装(反射的缺点),setAccessible(true)

测试用例

public class User {
    
    

	public int id;
	
	private String name;
	
	String address;
	
	protected int sno;
	
	public User() {
    
    }
	
	public User(int id, String name, String address, int sno) {
    
    
		super();
		this.id = id;
		this.name = name;
		this.address = address;
		this.sno = sno;
	}

	@Override
	public String toString() {
    
    
		return "User [id=" + id + ", name=" + name + ", address=" + address + ", sno=" + sno + "]";
	}

	@Override
	public int hashCode() {
    
    
		final int prime = 31;
		int result = 1;
		result = prime * result + ((address == null) ? 0 : address.hashCode());
		result = prime * result + id;
		result = prime * result + ((name == null) ? 0 : name.hashCode());
		result = prime * result + sno;
		return result;
	}

	@Override
	public boolean equals(Object obj) {
    
    
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		User other = (User) obj;
		if (address == null) {
    
    
			if (other.address != null)
				return false;
		} else if (!address.equals(other.address))
			return false;
		if (id != other.id)
			return false;
		if (name == null) {
    
    
			if (other.name != null)
				return false;
		} else if (!name.equals(other.name))
			return false;
		if (sno != other.sno)
			return false;
		return true;
	}
}
import java.lang.reflect.Field;

public class ReflectTest {
    
    
	public static void main(String[] args) throws Exception {
    
    
		Class usrClass = Class.forName("com.lzj.reflect.pojo.User");
		// 获取对象
		Object object = usrClass.newInstance();
		// 获取属性
		Field field = usrClass.getDeclaredField("id");
		// 赋值
		field.set(object, 34);
		// 获取属性值
		System.out.println(field.get(object));
		
		/*
		 * 访问私有属性
		 * 无法直接访问,抛出IllegalAccessException异常
		 * 需要打破封装
		 */
		Field field2 = usrClass.getDeclaredField("name");
		// 打破封装
		field2.setAccessible(true);
		
		field2.set(object, "lzj");
		System.out.println(field2.get(object));
	}
}

猜你喜欢

转载自blog.csdn.net/LvJzzZ/article/details/108975740