cn.fql.utility.ClassUtility.java Source code

Java tutorial

Introduction

Here is the source code for cn.fql.utility.ClassUtility.java

Source

/*
 * File: $RCSfile$
 *
 * Copyright (c) 2005 Wincor Nixdorf International GmbH,
 * Heinz-Nixdorf-Ring 1, 33106 Paderborn, Germany
 * All Rights Reserved.
 *
 * This software is the confidential and proprietary information
 * of Wincor Nixdorf ("Confidential Information"). You shall not
 * disclose such Confidential Information and shall use it only in
 * accordance with the terms of the license agreement you entered
 * into with Wincor Nixdorf.
 */
package cn.fql.utility;

import org.apache.commons.lang.ClassUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.PropertyUtils;

import java.util.Map;
import java.util.HashMap;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.Iterator;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.beans.PropertyDescriptor;
import java.beans.IntrospectionException;
import java.beans.BeanInfo;
import java.beans.Introspector;
import java.lang.reflect.Method;

/**
 * The class <code>cn.fql.utility.ClassUtility</code>
 *
 * @author User, WN ASP SSD
 * @version $Revision$
 */
public class ClassUtility {
    private static Map classTypeMap = new HashMap();

    /**
     * Constructor
     */
    private ClassUtility() {

    }

    static {
        classTypeMap.put(String.class.getName(), String.class);
        classTypeMap.put(Boolean.class.getName(), Boolean.class);
        classTypeMap.put(BigDecimal.class.getName(), BigDecimal.class);
        classTypeMap.put(Date.class.getName(), Date.class);
        classTypeMap.put(Integer.class.getName(), Integer.class);
        classTypeMap.put(Timestamp.class.getName(), Timestamp.class);
        classTypeMap.put(int.class.getName(), int.class);
        classTypeMap.put(long.class.getName(), long.class);
        classTypeMap.put(boolean.class.getName(), boolean.class);
    }

    /**
     * Return is one class implements a class or extends a class
     *
     * @param currClass  current class
     * @param superClass the super class or interface
     * @return the result
     */
    public static boolean isRelationClass(Class currClass, Class superClass) {
        boolean result = false;
        if (currClass != null) {
            if (currClass.equals(superClass)) {
                result = true;
            } else {
                // find in interface
                Class[] interfaces = currClass.getInterfaces();
                for (int i = 0; i < interfaces.length; i++) {
                    Class currInterface = interfaces[i];
                    if (currInterface.equals(superClass)) {
                        result = true;
                    }
                }

                if (!result) {
                    //find in superclass
                    if (currClass.equals(Object.class)) {
                        result = false;
                    } else {
                        List superClasses = ClassUtils.getAllSuperclasses(currClass);
                        if (!CollectionUtils.isEmpty(superClasses)) {
                            Class currSuperClass = (Class) superClasses.get(0);
                            if (currSuperClass == null) {
                                System.out.println("Super Class is null");
                                result = false;
                            } else {
                                result = isRelationClass(currSuperClass, superClass);
                            }
                        }
                    }
                }
            }
        }
        return result;
    }

    /**
     * Export property desc of specified class
     *
     * @param beanClass specified class
     * @return @see java.beans.BeanInfo#getPropertyDescriptors
     * @throws java.beans.IntrospectionException
     *          if there is exception occurs
     */
    public static PropertyDescriptor[] exportPropertyDesc(Class beanClass) throws IntrospectionException {
        BeanInfo bi;
        PropertyDescriptor[] pds;
        bi = Introspector.getBeanInfo(beanClass);
        pds = bi.getPropertyDescriptors();
        return pds;
    }

    /**
     * Import value to object according specified  <code>org.xml.sax.Attributes</code>
     *
     * @param obj  specified object instance
     * @param atts <code>org.xml.sax.Attributes</code>
     */
    public static void importValueFromAttribute(Object obj, org.xml.sax.Attributes atts) {
        if (atts != null) {
            PropertyDescriptor[] pds;
            try {
                pds = exportPropertyDesc(obj.getClass());
                if (pds != null && pds.length > 0) {
                    for (int i = 0; i < pds.length; i++) {
                        PropertyDescriptor pd = pds[i];
                        String strValue = atts.getValue(pd.getName());
                        if (strValue != null) {
                            Method setter = pd.getWriteMethod();
                            if (setter != null) {
                                Object value = ConvertUtils.convert(strValue, pd.getPropertyType());
                                Object[] params = { value };
                                setter.invoke(obj, params);
                            }
                        }
                    }
                }
            } catch (Exception e) {
                System.out.println(e.getMessage());
            }
        }
    }

    /**
     * Import specified and property name to a specified object
     *
     * @param obj          object instance
     * @param propertyName name of property
     * @param value        property value
     */
    public static void setValue(Object obj, String propertyName, Object value) {
        try {
            String _pName = StringUtility.recoverIllegalPropertyName(propertyName);
            PropertyUtils.setProperty(obj, _pName, value);
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }

    /**
     * Return property type of a special property
     *
     * @param obj          Object instance
     * @param propertyName Name of property
     * @return Property clazz
     */
    public static Class getPropertyType(Object obj, String propertyName) {
        Class clazz = null;
        try {
            String _pName = StringUtility.recoverIllegalPropertyName(propertyName);
            clazz = PropertyUtils.getPropertyType(obj, _pName);
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        return clazz;
    }

    /**
     * Export property value of specified object
     *
     * @param obj          object instance
     * @param propertyName property name
     * @return property value of object
     */
    public static Object getPropertyValue(Object obj, String propertyName) {
        Object result = null;
        if (propertyName != null) {
            try {
                result = PropertyUtils.getProperty(obj, propertyName);
            } catch (Exception e) {
                System.out.println(e.getMessage());
            }
        }
        return result;
    }

    /**
     * Return class with specified type
     *
     * @param type Class type
     * @return Class
     * @throws ClassNotFoundException Exception occurs when class is not found.
     */
    public static Class getClazz(String type) throws ClassNotFoundException {
        Class clazz = (Class) classTypeMap.get(type);
        if (clazz == null) {
            clazz = Class.forName(type);
        }
        return clazz;
    }

    /**
     * compare property of two object
     *
     * @param obj1         object instance
     * @param obj2         object instance
     * @param propertyName name of property which is required to be compared
     * @return boolean value
     */
    public static boolean comparePropertyEqual(Object obj1, Object obj2, String propertyName) {
        Object value1 = getPropertyValue(obj1, propertyName);
        Object value2 = getPropertyValue(obj2, propertyName);
        boolean isEqual = true;
        if (value1 != null ^ value2 != null) {
            isEqual = false;
        } else {
            if (value1 != null) {
                isEqual = value1.equals(value2);
            }
        }
        return isEqual;
    }

    /**
     * Import data to this object from input Map
     *
     * @param obj    object
     * @param values <code>values</code>
     */
    public static void importValueFromMap(Object obj, Map values) {
        if (values != null) {
            PropertyDescriptor[] pds;
            try {
                pds = exportPropertyDesc(obj.getClass());
                if (pds != null && pds.length > 0) {
                    Set keySet = values.keySet();
                    Iterator it = keySet.iterator();
                    while (it.hasNext()) {
                        String name = (String) it.next();
                        for (int i = 0; i < pds.length; i++) {
                            PropertyDescriptor pd = pds[i];
                            if (pd.getName().equals(name)) {
                                Method setter = pd.getWriteMethod();
                                if (setter != null) {
                                    Object[] params = { values.get(name) };
                                    setter.invoke(obj, params);
                                }
                                break;
                            }
                        }
                    }
                }
            } catch (Exception e) {
                System.out.println(e.getMessage());
            }
        }
    }

    /**
     * Export property value of specified object to a map
     *
     * @param obj            object instance
     * @param isWithNullable denote whether it is required to skip null value
     * @return map instance includes property value
     */
    public static Map collectAsMap(Object obj, boolean isWithNullable) {
        Map mapOutput = new HashMap();
        PropertyDescriptor[] pds;
        try {
            pds = exportPropertyDesc(obj.getClass());
            for (int i = 0; i < pds.length; i++) {
                PropertyDescriptor pd = pds[i];
                Method getter = pd.getReadMethod();
                if (getter != null && !pd.getName().equals("class")) {
                    Object value = getter.invoke(obj);
                    if (value == null) {
                        if (!isWithNullable) {
                            continue;
                        }
                    }
                    if (pd.getPropertyType().equals(String.class) && value == null) {
                        value = "";
                    }
                    mapOutput.put(pd.getName(), value);
                }
            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        return mapOutput;
    }

    /**
     * Return primitive class by specified class name
     * This method has better performance than java reflection.
     *
     * @param className class name
     * @return Primitive class
     */
    public static Class getPrimitiveClass(String className) {
        Class c;
        if ("java.lang.Integer".equals(className)) {
            c = Integer.class;
        } else if ("java.lang.Long".equals(className)) {
            c = Long.class;
        } else if ("java.math.BigDecimal".equals(className)) {
            c = BigDecimal.class;
        } else if ("java.util.Date".equals(className)) {
            c = Date.class;
        } else if ("java.sql.Timestamp".equals(className)) {
            c = Timestamp.class;
        } else {
            c = String.class;
        }
        return c;
    }
}
/**
 * History:
 *
 * $Log$
 */