集册 Java实例教程 从bean对象获取属性值;

从bean对象获取属性值;

欢马劈雪     最近更新时间:2020-01-02 10:19:05

652
从bean对象获取属性值;
/** from 
n o w  j a v a  . c o m**/

/**

 *all rights reserved,@copyright 2003

 */

import java.lang.reflect.Method;

import java.lang.reflect.InvocationTargetException;

import java.util.ArrayList;

import java.util.HashMap;


public class Main{

    public static void main(String[] argv) throws Exception{

        Object bean = "nowjava.com";

        String propertyName = "nowjava.com";

        System.out.println(getBeanProperty(bean,propertyName));

    }

    public static final String PROPERTY_GET_METHOD_PREFIX = "get";

    public static final String PROPERTY_IS_METHOD_PREFIX = "is";

    /**

     * get a property's value from a bean object;

     *

     * @param bean the bean object;

     * @param propertyName the property name;

     * @return the Value of the property;

     * @throws NoSuchPropertyException

     * @throws GetPropertyException

     */

    public static Object getBeanProperty(Object bean, String propertyName)

            throws NoSuchPropertyException, GetPropertyException {

        //try getXXX first;

        String methodName = BeanUtil.PROPERTY_GET_METHOD_PREFIX

                + Character.toUpperCase(propertyName.charAt(0))
                /** from 
                时代Java - nowjava.com**/

                + propertyName.substring(1);

        Class[] clz = new Class[0];

        try {

            Method m = getMethod(bean, methodName, clz);

            return m.invoke(bean, new Object[0]);

        } catch (NoSuchMethodException e) {


        } catch (IllegalAccessException e) {

            throw new GetPropertyException("illegal access to property:"

                    + propertyName);

        } catch (InvocationTargetException e) {

            throw new GetPropertyException(e.getTargetException()

                    .getMessage());

        }


        //if no getXXX, then try isXXX;

        methodName = BeanUtil.PROPERTY_IS_METHOD_PREFIX

                + Character.toUpperCase(propertyName.charAt(0))

                + propertyName.substring(1);

        try {

            Method m = getMethod(bean, methodName, clz);

            return m.invoke(bean, new Object[0]);

        } catch (NoSuchMethodException e) {

            throw new NoSuchPropertyException(bean.getClass().getName(),

                    propertyName);

        } catch (IllegalAccessException e) {

            throw new GetPropertyException("illegal access to property:"

                    + propertyName);

        } catch (InvocationTargetException e) {

            throw new GetPropertyException(e.getTargetException()

                    .getMessage());

        }

    }

    /**

     *

     *

     * @param o

     * @param methodName

     * @param paramTypes

     * @return

     * @throws NoSuchMethodException

     */

    public static Method getMethod
展开阅读全文