Java examples for Reflection:Java Bean
get Mapped Property of Java Bean
//package com.java2s; 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); 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); }/*from w ww .jav a 2s . co m*/ 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]; } return null; } public static PropertyDescriptor[] getPropertyDescriptors(Object bean) { BeanInfo beanInfo = null; try { beanInfo = Introspector.getBeanInfo(bean.getClass()); } catch (IntrospectionException e) { return (new PropertyDescriptor[0]); } PropertyDescriptor[] descriptors = beanInfo .getPropertyDescriptors(); return descriptors; } }