集册 Java实例教程 获取Java Bean属性

获取Java Bean属性

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

432
获取Java Bean属性


//package com.nowjava;/*n o w j a v a . c o m - 时  代  Java 提供*/

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 = "nowjava.com";

        Class beanClass = String.class;

        System.out.println(getJavaBeanProperties(bean, beanClass));

    }


    public static HashMap getJavaBeanProperties(Object bean, Class beanClass) {

        HashMap valueMap = new HashMap();

        if (!beanClass.isInstance(bean)) {

            return valueMap;

        }

        PropertyDescriptor propDesc = null;/*nowjava - 时代Java 提 供*/

        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;

                pro
展开阅读全文