欢迎大家来到IT世界,在知识的湖畔探索吧!
以下示例演示如何从 填充 Java Bean 字段。java.util.Map
例子
package com.logicbig.example;
public class Person {
private String name;
private int age;
private String 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 "Person{" +
"name='" + name + '\'' +
", age=" + age +
", address='" + address + '\'' +
'}';
}
}
欢迎大家来到IT世界,在知识的湖畔探索吧!
欢迎大家来到IT世界,在知识的湖畔探索吧!package com.logicbig.example;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
public class MapToBeanUtil {
public static void main(String[] args) {
Map<String, Object> map = new HashMap<>();
map.put("name", "Tina");
map.put("age", 30);
map.put("address", "101 Sun Street, Yellow Town");
Person person = toBean(map, Person.class);
System.out.println(person);
}
public static <T> T toBean(Map<String, Object> beanPropMap, Class<T> type) {
try {
T beanInstance = type.getConstructor().newInstance();
for (Object k : beanPropMap.keySet()) {
String key = (String) k;
Object value = beanPropMap.get(k);
if (value != null) {
try {
Field field = type.getDeclaredField(key);
field.setAccessible(true);
field.set(beanInstance, value);
field.setAccessible(false);
} catch (Exception e) {
e.printStackTrace();
}
}
}
return beanInstance;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
Person{name='Tina', age=30, address='101 Sun Street, Yellow Town'}
免责声明:本站所有文章内容,图片,视频等均是来源于用户投稿和互联网及文摘转载整编而成,不代表本站观点,不承担相关法律责任。其著作权各归其原作者或其出版社所有。如发现本站有涉嫌抄袭侵权/违法违规的内容,侵犯到您的权益,请在线联系站长,一经查实,本站将立刻删除。 本文来自网络,若有侵权,请联系删除,如若转载,请注明出处:https://itzsg.com/37730.html