集册 Java实例教程 设置Java Bean属性

设置Java Bean属性

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

580
设置Java Bean属性
//from 时 代 J a v a 公 众 号 - nowjava.com


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;

import java.lang.reflect.Modifier;

import java.math.BigDecimal;

import java.math.BigInteger;

import java.util.Arrays;

import java.util.HashMap;

import java.util.List;

import java.util.Map;//from nowjava - 时  代  Java


public class Main{

    private static void setProperty(Object target,

            PropertyDescriptor targetPd, Object value)

            throws IllegalAccessException, InvocationTargetException {

        Method writeMethod = targetPd.getWriteMethod();

        if (!Modifier.isPublic(writeMethod.getDeclaringClass()

                .getModifiers())) {

            writeMethod.setAccessible(true);

        }

        writeMethod.invoke(

                target,

                new Object[] { convert(value,

                        writeMethod.getParameterTypes()[0]) });

    }

    private static Object convert(Object value, Class<?> targetType) {

        if (value == null)

            return null;

        if (targetType == String.class) {

            return value.toString();

        } else {

            return convert(value.toString(), targetType);

        }

    }

    private static Object convert(String value, Class<?> targetType) {

        if (targetType == Byte.class || targetType == byte.class) {

            return new Byte(value);

        }

        if (targetType == Short.class || targetType == short.class) {

            return new Short(value);

        }

        if (targetType == Integer.class || targetType == int.class) {

            return new Integer(value);

        }

        if (targetType == Long.class || targetType == long.class) {

            return new Long(value);

        }

        if (targetType == Float.class || targetType == float.class) {

            return new Float(value);

        }

        if (targetType == Double.class || targetType == double.class) {

            return new Double(value);

        }

        if (targetType == BigDecimal.class) {

            return new BigDecimal(value);

        }

        if (targetType == BigInteger.class) {

            return BigInteger.valueOf(Long.parseLong(value));

        }

        if (targetType == Boolean.class || targetType == boolean.class) {

            return new Boolean(value);

        }

        if (targetType == boolean.class) {

            return 
展开阅读全文