访问对象属性
- 给属性赋值,使用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));
Field field2 = usrClass.getDeclaredField("name");
field2.setAccessible(true);
field2.set(object, "lzj");
System.out.println(field2.get(object));
}
}