All Downloads are FREE. Search and download functionalities are using the official Maven repository.

patterntesting.runtime.util.ReflectionHelper Maven / Gradle / Ivy

Go to download

PatternTesting Runtime (patterntesting-rt) is the runtime component for the PatternTesting framework. It provides the annotations and base classes for the PatternTesting testing framework (e.g. patterntesting-check, patterntesting-concurrent or patterntesting-exception) but can be also used standalone for classpath monitoring or profiling. It uses AOP and AspectJ to perform this feat.

The newest version!
/*
 * $Id: ReflectionHelper.java,v 1.7 2009/12/19 22:34:09 oboehm Exp $
 *
 * Copyright (c) 2009 by Oliver Boehm
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express orimplied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * (c)reated 09.03.2009 by oliver ([email protected])
 */
package patterntesting.runtime.util;

import java.lang.reflect.*;
import java.util.*;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.impl.LogFactoryImpl;

/**
 * This class is a helper class to access some fields via reflection. Normally
 * you should avoid reflection. Handle with care if you use it.
 *
 * @author oliver
 * @since 09.03.2009
 * @version $Revision: 1.7 $
 */
public class ReflectionHelper {

     private static final Log log = LogFactoryImpl.getLog(ReflectionHelper.class);

    /**
     * Tries to get the wanted field. Before it is returned the acc
     *
     * @param cl the cl
     * @param name the name
     *
     * @return the wanted field
     *
     * @throws NoSuchFieldException the no such field exception
     */
    public static Field getField(Class cl, String name)
            throws NoSuchFieldException {
        try {
            Field field = cl.getDeclaredField(name);
            field.setAccessible(true);
            return field;
        } catch (NoSuchFieldException e) {
            Class superclass = cl.getSuperclass();
            if (superclass == null) {
                throw e;
            } else {
                if (log.isTraceEnabled()) {
                    log.trace("using " + superclass + " to get " + cl.getName()
                            + "." + name + "...");
                }
                return ReflectionHelper.getField(superclass, name);
            }
        }
    }

    /**
     * If it can it returns the value of the given field. If not it throws an
     * exception.
     *
     * @param obj the obj
     * @param name the name
     *
     * @return the field value
     *
     * @throws NoSuchFieldException the no such field exception
     * @throws IllegalAccessException the illegal access exception
     * @throws IllegalArgumentException the illegal argument exception
     */
    public static Object getFieldValue(Object obj, String name)
            throws NoSuchFieldException, IllegalArgumentException,
            IllegalAccessException {
        Field field = ReflectionHelper.getField(obj.getClass(), name);
        return field.get(obj);
    }

    /**
     * To get all uninitialized field you can call this method.
     *
     * @param obj the object where to get the fields from
     *
     * @return a collecion of unitialized fields (can be empty)
     */
    public static Collection getUninitializedNonStaticFields(Object obj) {
        Collection unitializedFields = new ArrayList();
        Field[] fields = obj.getClass().getDeclaredFields();
        for (int i = 0; i < fields.length; i++) {
            try {
                fields[i].setAccessible(true);
                if ((fields[i].get(obj) == null) && !isStatic(fields[i])) {
                    unitializedFields.add(fields[i]);
                }
            } catch (IllegalArgumentException e) {
                log.info(e + " => " + fields[i] + " ignored");
            } catch (IllegalAccessException e) {
                log.debug("can't access " + fields[i] + " => ignored");
            }
        }
        return unitializedFields;
    }

    private static boolean isStatic(Field field) {
        int m = field.getModifiers();
        return Modifier.isStatic(m);
    }

    /**
     * To short string.
     *
     * @param field the field
     *
     * @return the string
     */
    public static String toShortString(Field field) {
        return field.getType().getSimpleName() + " " + field.getName();
    }

    /**
     * To short string.
     *
     * @param fields the fields
     *
     * @return the string
     */
    public static String toShortString(Collection fields) {
        StringBuffer sbuf = new StringBuffer();
        for (Iterator iterator = fields.iterator(); iterator.hasNext();) {
            Field field = iterator.next();
            sbuf.append(", ");
            sbuf.append(toShortString(field));
        }
        return sbuf.substring(2);
    }

    /**
     * Gets the method.
     *
     * @param cl e.g. class java.lang.ClassLoader
     * @param name e.g. "getPackages"
     *
     * @return a Method object
     *
     * @throws NoSuchMethodException the no such method exception
     */
	public static Method getMethod(Class cl, String name) throws NoSuchMethodException {
	    try {
	        return cl.getDeclaredMethod(name);
	    } catch (NoSuchMethodException e) {
	        Class superclass = cl.getSuperclass();
	        if (superclass == null) {
	            throw e;
	        } else {
	            return getMethod(superclass, name);
	        }
	    }
	}

}

/**
 * $Log: ReflectionHelper.java,v $
 * Revision 1.7  2009/12/19 22:34:09  oboehm
 * trailing spaces removed
 *
 * Revision 1.6  2009/09/25 14:49:43  oboehm
 * javadocs completed with the help of JAutodoc
 *
 * Revision 1.5  2009/09/18 13:54:52  oboehm
 * javadoc warnings fixed
 *
 * Revision 1.4  2009/08/03 06:12:37  oboehm
 * partially support of WLS classload (via getClasspathFromPackages)
 *
 * $Source: /cvsroot/patterntesting/PatternTesting08/patterntesting-rt/src/main/java/patterntesting/runtime/util/ReflectionHelper.java,v $
 */




© 2015 - 2024 Weber Informatics LLC | Privacy Policy