1、public 属性
Person 类
public class Person {
public int age = 0;
public String name = "helloword";
public int id = 1234;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
Test 类
public class Test {
public static void main(String[] args) {
//这么做的前期是 Person的属性必须是 public的
Person person = new Person();
System.out.println("-------------------赋值前---------------------------");
System.out.println(person.getName()); //helloword
System.out.println(person.getAge()); //0
System.out.println(person.getId()); //1234
//用于储值的map对象
Map map = new HashMap();
map.put("name", "张三");
map.put("age", 18);
//取得该对象反射的 Fields
Field[] declaredFields = person.getClass().getDeclaredFields();
for (Field f : declaredFields) {
String perName = f.getName();
Object o = map.get(perName);
if (o != null) {
try {
f.set(person, o);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
System.out.println("-------------------赋值后---------------------------");
System.out.println(person.getName()); //张三
System.out.println(person.getAge()); //18
System.out.println(person.getId()); //1234
}
}
2、private 属性 ,须借助与该类的public setter
Person类
public class Person {
private int age = 0;
private String name = "helloword";
priavte int id = 1234;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
Test类
public class Test {
public static void main(String[] args) {
Person person = new Person();
System.out.println("-------------------赋值前---------------------------");
System.out.println(person.getName()); //helloword
System.out.println(person.getAge()); //0
System.out.println(person.getId()); //1234
//用于储值的map对象
Map map = new HashMap();
map.put("name", "张三");
map.put("age", 18);
//取得该对象反射的 Fields
Class Person = person.getClass();
Field[] declaredFields = Person.getDeclaredFields();
//用于存储method的
Map<String,Method> mapMethod = new HashMap();
try {
Method[] declaredMethods = Person.getDeclaredMethods();
//将method放入mapMethod 中方便下面调用
for(Method m : declaredMethods){
mapMethod.put(m.getName().toLowerCase(),m);
}
} catch (Exception e) {
e.printStackTrace();
}
for (Field f : declaredFields) {
String perName = f.getName();
Object o = map.get(perName);
if (o != null) {
try {
mapMethod.get("set"+perName.toLowerCase()).invoke(person,o);
} catch (Exception e) {
e.printStackTrace();
}
}
}
System.out.println("-------------------赋值后---------------------------");
System.out.println(person.getName()); //张三
System.out.println(person.getAge()); //18
System.out.println(person.getId()); //1234
}
}