JAvaはBeanInfoを用いてbeanエンティティとmap間の相互変換を実現する
3245 ワード
JAvaはBeanInfoを用いてbeanエンティティとmap間の相互変換を実現する.public interface BeanInfoは、そのbeanに関する明示的な情報を提供することを望むbeanインプリメンテーションは、このBeanInfoインタフェースを実装し、そのbeanに関する方法、属性、イベントなどの明示的な情報を提供するBeanInfoクラスを提供することができる.
何気なく巨牛の人工知能のチュートリアルを見つけて、思わず共有してあげました.教程は基礎がゼロで、分かりやすくて、しかもとても面白くてユーモアがあって、小説を読むようです!すごいと思って、みんなに分かち合いました.ここをクリックするとチュートリアルにジャンプできます.
import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import com.bh.bean.User;
public class Test {
/**
* bean map
*/
public Test() {
try {
Map user=beanTransformToMap(new User(1, "zs"));
Iterator> iterator = user.entrySet().iterator();
while(iterator.hasNext()){
Entry next = iterator.next();
System.out.println(next.getKey()+" "+next.getValue());
}
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException
| IntrospectionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**map
* @param map
* @return
* @throws IllegalAccessException
* @throws IllegalArgumentException
* @throws InvocationTargetException
* @throws IntrospectionException
*/
private User mapTransformToBean(Map map) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, IntrospectionException{
User user=new User();
BeanInfo beanInfo = Introspector.getBeanInfo(user.getClass());
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
for (PropertyDescriptor property : propertyDescriptors) {
String key = property.getName();
if (map.containsKey(key)) {
Object value = map.get(key);
// property setter
Method setter = property.getWriteMethod();
setter.invoke(user, value);
}
}
return user;
}
/** map
* @param user
* @return
* @throws IllegalAccessException
* @throws IllegalArgumentException
* @throws InvocationTargetException
* @throws IntrospectionException
*/
private Map beanTransformToMap(User user) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, IntrospectionException{
Map map = new HashMap();
BeanInfo beanInfo = Introspector.getBeanInfo(user.getClass());
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
for (PropertyDescriptor property : propertyDescriptors) {
String key = property.getName();
// class
if (!key.equals("class")) {
// property getter
Method getter = property.getReadMethod();
Object value = getter.invoke(user);
map.put(key, value);
}
}
return map;
}
public static void main(String[] args) {
new Test();
}
}
何気なく巨牛の人工知能のチュートリアルを見つけて、思わず共有してあげました.教程は基礎がゼロで、分かりやすくて、しかもとても面白くてユーモアがあって、小説を読むようです!すごいと思って、みんなに分かち合いました.ここをクリックするとチュートリアルにジャンプできます.