集册 Java实例教程 映射到Bean

映射到Bean

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

500
映射到Bean
//时代Java公众号 - nowjava.com

//package com.nowjava;

import java.beans.BeanInfo;

import java.beans.IntrospectionException;

import java.beans.Introspector;

import java.beans.PropertyDescriptor;


import java.lang.reflect.Method;


import java.util.Map;


public class Main {


    public static <T> T mapToBean(Map<?, ?> map, Class<T> bean)

            throws InstantiationException, IllegalAccessException,

            IntrospectionException {

        BeanInfo beanInfo = Introspector.getBeanInfo(bean);

        T obj = bean.newInstance();

        PropertyDescriptor[] propertyDescriptors = beanInfo

                .getPropertyDescriptors();/** nowjava.com - 时代Java 提 供 **/

        for (int i = 0; i < propertyDescriptors.length; i++) {

            PropertyDescriptor descriptor = propertyDescriptors[i];

            Method method = descriptor.getWriteMethod();

            String name = descriptor.getName();

            if (map.containsKey(name)) {

                Class<?>[] types = method.getParameterTypes();

                for (int x = 0; x < types.length; x++) { //

                    Object value = map.get(name);

                    try {

                        method.invoke(obj, new Object[] { value });

                    } catch (Exception e) {

                        System.out.println(
展开阅读全文