⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 reflectionutils.java

📁 日常的办公系统 应用工作流框架等增加员工的基本信息、培训信息、奖罚信息、薪资信息
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
/* * Copyright (c) 2005, John Mettraux, OpenWFE.org * All rights reserved. *  * Redistribution and use in source and binary forms, with or without  * modification, are permitted provided that the following conditions are met: *  * . Redistributions of source code must retain the above copyright notice, this *   list of conditions and the following disclaimer.   *  * . Redistributions in binary form must reproduce the above copyright notice,  *   this list of conditions and the following disclaimer in the documentation  *   and/or other materials provided with the distribution. *  * . Neither the name of the "OpenWFE" nor the names of its contributors may be *   used to endorse or promote products derived from this software without *   specific prior written permission. *  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE  * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE  * POSSIBILITY OF SUCH DAMAGE. * * $Id: ReflectionUtils.java,v 1.14 2005/07/19 07:30:27 jmettraux Exp $ *///// ReflectionUtils.java//// john.mettraux@openwfe.org//// generated with // jtmpl 1.1.01 2004/05/19 (john.mettraux@openwfe.org)//package openwfe.org;import java.lang.reflect.Method;/** * Methods for instatiating classes on the fly... * * <p><font size=2>CVS Info : * <br>$Author: jmettraux $ * <br>$Id: ReflectionUtils.java,v 1.14 2005/07/19 07:30:27 jmettraux Exp $ </font> * * @author john.mettraux@openwfe.org */public abstract class ReflectionUtils{    private final static org.apache.log4j.Logger log = org.apache.log4j.Logger        .getLogger(ReflectionUtils.class.getName());    /**     * contains simply 'class', this is supposed to be the name of the parameter     * holding the classname for the initObject(java.util.Map params) method.     */    public final static String P_CLASS        = "class";    private final static String IS = "is";    private final static String GET = "get";    private final static String SET = "set";    //    // caching the pair of get/set methods for each bean class    private static java.util.Map fieldCache = new java.util.HashMap();    //    // METHODS    /**     * finds the init(java.util.Map initParameters) method in an object     * and invokes it     */    public static Object initObject         (Object o, java.util.Map initParameters)    throws         NoSuchMethodException,         IllegalAccessException,         java.lang.reflect.InvocationTargetException    {        //        // not a permission        Class clazz = o.getClass();        java.lang.reflect.Method initMethod =             clazz.getMethod("init", new Class[] { java.util.Map.class });        //log.debug("------ found the init() method");        initMethod.invoke(o, new Object[] { initParameters });        //log.debug("------ init() method invocation seems successful");        return o;    }    /**     * This method is intended for classes with constructor that takes no     * parameter and a init(java.util.Map initParameters) method.     * By using this method, you can build an instance of such a class very     * easily.     */    public static Object initObjectOfClass        (final String className, final java.util.Map initParameters)    throws         Exception    {        Class clazz = Class.forName(className);        Object instance = clazz.newInstance();        return initObject(instance, initParameters);    }    /**     * init an object whose class is contained in a P_CLASS named parameter      * (usually 'class')     */    public static Object initObject         (final java.util.Map initParameters)    throws         Exception     {        final String className = (String)initParameters.get(P_CLASS);        if (className == null)        {            throw new IllegalArgumentException                ("There is no parameter '"+P_CLASS+                 "' ("+ReflectionUtils.class.getName()+                 ".P_CLASS). Cannot init instance.");        }        return initObjectOfClass(className, initParameters);    }    /**     * A reflective method.     *      * Customer c = new Customer("john");     * Object o = Utils.getAttribute(c, "name");     * ...     * o will yield the value "john" (because "john".equals(c.getName()))     * ...     */    public static Object getAttribute         (Object o, String attributeName)    throws         NoSuchMethodException,         IllegalAccessException,         java.lang.reflect.InvocationTargetException    {        Class clazz = o.getClass();        String methodName =             "get" +            attributeName.substring(0, 1).toUpperCase() +            attributeName.substring(1);        java.lang.reflect.Method getMethod =             clazz.getMethod(methodName, new Class[] {});        return getMethod.invoke(o, new Object[] {});    }    /**     * Given an instance, the name of one of its attribute (property) sets a      * new value for it.     */    public static Object setAttribute         (Object o, String attributeName, Object value)    throws         Exception    {        Class clazz = o.getClass();        String methodName =             "set" +            attributeName.substring(0, 1).toUpperCase() +            attributeName.substring(1);        java.lang.reflect.Method method = null;        Class parameterClass = null;        java.lang.reflect.Method[] methods = clazz.getMethods();        for (int i=0; i<methods.length; i++)        {            java.lang.reflect.Method m = methods[i];            if (m.getName().equals(methodName) &&                m.getParameterTypes().length == 1)            {                method = m;                parameterClass = m.getParameterTypes()[0];                break;            }        }        if (method == null)        {            throw new NoSuchMethodException                ("No method named '"+methodName+                 "' with 1! parameter in class '"+clazz.getName()+"'");        }        // narrow value type        value = buildInstance(parameterClass, value);        return method.invoke(o, new Object[] { value });    }    /**     * Returns a list of attribute (field) names for a given object.     */    public static java.util.List listAttributes (final Object o)    {        final Class clazz = o.getClass();        final java.lang.reflect.Method[] methods = clazz.getMethods();        final java.util.List attributeNames =             new java.util.ArrayList(methods.length);        for (int i=0; i<methods.length; i++)        {            final java.lang.reflect.Method m = methods[i];            if (m.getName().startsWith("get") &&                m.getParameterTypes().length == 0)            {                final String attributeName =                     m.getName().substring(3, 4).toLowerCase() +                     m.getName().substring(4);                attributeNames.add(attributeName);            }        }        return attributeNames;    }    /**     * tries to locate a constructor with a single parameter     * in the targetClass and to build a target object then     */    public static Object buildInstance        (Class targetClass, Object value)    throws         Exception    {        /*        log.debug            ("buildInstance() - targetClass is '"+targetClass.getName()+"'");        log.debug            ("buildInstance() - value.toString() is '"+value+"'");        */        if (value == null)         {            /*            log.debug                ("buildInstance() - returning null");            */            return null;        }        if (targetClass.isAssignableFrom(value.getClass()))            return value; // fast lane        java.lang.reflect.Constructor[] constructors =             targetClass.getConstructors();        java.lang.reflect.Constructor constructor = null;        java.lang.reflect.Constructor secondMatchConstructor = null;

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -