获取Java Bean的映射属性
/** 来自 N o w J a v a . c o m - 时 代 Java**/ //package com.nowjava; 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; public class Main { private static final String MAPPED_DELIM = "("; private static final String MAPPED_DELIM2 = ")"; public static Object getMappedProperty(Object bean, String name) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException { int delim = name.indexOf(MAPPED_DELIM); int delim2 = name.indexOf(MAPPED_DELIM2);/** 来 自 nowjava - 时 代 Java**/ if ((delim < 0) || (delim2 <= delim)) throw new IllegalArgumentException("Invalid mapped property '" + name + "'"); String subscript = name.substring(delim + 1, delim2); name = name.substring(0, delim); return getMappedProperty(bean, name, subscript); } public static Object getMappedProperty(Object bean, String name, String key) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException { PropertyDescriptor propertyDescriptor = getPropertyDescriptor(bean, name); if (propertyDescriptor == null) throw new IllegalArgumentException("No property:" + name); Method readMethod = propertyDescriptor.getReadMethod(); if (readMethod == null) throw new IllegalArgumentException( "No readMethod for property:" + name); Object map = readMethod.invoke(bean, new Object[0]); if (!(map instanceof java.util.Map)) throw new IllegalArgumentException("Property '" + name + "' is not mapped"); return ((java.util.Map<?, ?>) map).get(key); } public static PropertyDescriptor getPropertyDescriptor(Object bean, String name) { PropertyDescriptor[] descriptors = getPropertyDescriptors(bean); for (int i = 0; i < descriptors.length; i++) { if (name.equals(descriptors[i].getName())) return descriptors[i]; }