Java examples for Reflection:Java Bean
get Java Bean Properties
//package com.java2s; import java.beans.PropertyDescriptor; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.HashMap; public class Main { public static void main(String[] argv) throws Exception { Object bean = "java2s.com"; Class beanClass = String.class; System.out.println(getJavaBeanProperties(bean, beanClass)); }// ww w . j a v a 2s. c o m public static HashMap getJavaBeanProperties(Object bean, Class beanClass) { HashMap valueMap = new HashMap(); if (!beanClass.isInstance(bean)) { return valueMap; } PropertyDescriptor propDesc = null; Field[] fields = beanClass.getDeclaredFields(); for (int i = 0; i < fields.length; i++) { try { propDesc = new PropertyDescriptor(fields[i].getName(), beanClass); } catch (Exception e) { } Method readMethod = propDesc.getReadMethod(); try { Object propValue = null; propValue = readMethod.invoke(bean, new Object[] {}); valueMap.put(fields[i].getName(), propValue); } catch (Exception e) { e.printStackTrace(); } } return valueMap; } }