答:基本思想,利用java中的反射机制
1.首先先自定义一个javabean,比如User
package aishang.reflect;
public class User {
private int age;
private String name;
public User() {
super();
}
public User(String name) {
super();
this.name = name;
}
public User(int age, String name) {
super();
this.age = age;
this.name = name;
}
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;
}
@Override
public String toString() {
return "User [age=" + age + ", name=" + 尺芦咐name + "]";
}
}
2.利用反射机制,读取javabean中的全部属性
Class> clazz = Class.forName("aishang.reflect.User");
MapmyMap = new HashMap ();
// 取得本类的全部属性
Field[] field = clazz.getDeclaredFields();
for (int i = 0; i < field.length; i++) {
// 权限修饰符
//int mo = field[i].getModifiers();
//String priv = Modifier.toString(mo);
// 属性类型
//Class> type = field[i].getType();
//System.out.println(priv + " " + type.getName() + " " + field[i].getName() + ";");
//-------------------------------------------------------------
//获取属性名:field[i].getName()
//将属性名封装到map中
myMap.put(field[i].getName(),null);
}
3.上述Map结构和User类的对应已经建立好,Map的Key就是User的属性名,但是Map中的Value还是空的,如果有需要可以将User对象的实例的值,映射到Map的Value中去,实例代码如下:
User user = new User();
user.setName("姜磊");
user.setAge(23);
for (Map.Entrym : myMap.entrySet()) {
String name = m.getKey();
//Object value = m.getValue();
//创建一属性描述器,将属性描述器映射到User类中
PropertyDescriptor pd = new PropertyDescriptor(name, User.class);
//得到getter属性
哗物 Method getter = pd.getReadMethod();
//将方法反射到User类中,读出属性的值
Object o = getter.invoke(user,null);
//System.out.println(o);
//给map重新赋值
myMap.put(name, o);
}
陵纯
System.out.println(myMap.get("age"));
System.out.println(myMap.get("name"));