Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
JBoss, Home of Professional Open Source Copyright 2008, Red Hat Middleware LLC, and individual contributors by the

Authors:
tag. See the copyright.txt in the distribution for a full listing of individual contributors. 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 or implied. See the License for the specific language governing permissions and limitations under the License.
 
 package org.jboss.weld.environment.servlet.util;
 
 
Reflection utilities

Author(s):
Pete Muir
 
 public abstract class Reflections {
 
     private Reflections() {
     }
 
     public static <T> T newInstance(String className) {
         try {
             return Reflections.<T>classForName(className).newInstance();
         } catch (InstantiationException e) {
             throw ..cannotInstantiateInstance(classNamee);
         } catch (IllegalAccessException e) {
             throw ..cannotInstantiateInstance(classNamee);
         }
     }
 
 
     @SuppressWarnings("unchecked")
     public static <T> Class<T> classForName(String name) {
 
         try {
             final ClassLoader tccl = Thread.currentThread().getContextClassLoader();
             if (tccl != null) {
                 return (Class<T>) tccl.loadClass(name);
             } else {
                 return (Class<T>) Class.forName(name);
             }
         } catch (ClassNotFoundException e) {
             throw ..cannotLoadClass(namee);
         } catch (LinkageError e) {
             throw ..cannotLoadClass(namee);
         }
     }

    
Search the class hierarchy for a method with the given name and arguments. Will return the nearest match, starting with the class specified and searching up the hierarchy.

Parameters:
clazz The class to search
name The name of the method to search for
args The arguments of the method to search for
Returns:
The method found, or null if no method is found
 
     public static Method findDeclaredMethod(Class<?> clazzString nameClass<?>... args) {
         for (Class<?> c = clazzc != null && c != Object.classc = c.getSuperclass()) {
             try {
                 return c.getDeclaredMethod(nameargs);
             } catch (NoSuchMethodException e) {
                 // No-op, continue the search
             }
         }
         return null;
     }

    
Search the class hierarchy for a field with the given name. Will return the nearest match, starting with the class specified and searching up the hierarchy.

Parameters:
clazz The class to search
name The name of the field to search for
Returns:
The field found, or null if no field is found
 
     public static Field findDeclaredField(Class<?> clazzString name) {
         for (Class<?> c = clazzc != null && c != Object.classc = c.getSuperclass()) {
             try {
                 return c.getDeclaredField(name);
             } catch (NoSuchFieldException e) {
                 // No-op, we continue looking up the class hierarchy
            }
        }
        return null;
    }
    public static <T> T invokeMethod(Method methodClass<T> expectedReturnTypeObject instanceObject... args) {
        try {
            return expectedReturnType.cast(method.invoke(instanceargs));
        } catch (IllegalAccessException ex) {
            throw new RuntimeException(buildInvokeMethodErrorMessage(methodinstanceargs), ex);
        } catch (IllegalArgumentException ex) {
            throw new IllegalArgumentException(buildInvokeMethodErrorMessage(methodinstanceargs), ex.getCause());
        } catch (InvocationTargetException ex) {
            throw new RuntimeException(buildInvokeMethodErrorMessage(methodinstanceargs), ex);
        } catch (NullPointerException ex) {
            NullPointerException ex2 = new NullPointerException(buildInvokeMethodErrorMessage(methodinstanceargs));
            ex2.initCause(ex.getCause());
            throw ex2;
        } catch (ExceptionInInitializerError e) {
            throw new RuntimeException(buildInvokeMethodErrorMessage(methodinstanceargs), e);
        }
    }
    private static String buildInvokeMethodErrorMessage(Method methodObject objObject... args) {
        StringBuilder message = new StringBuilder(String.format("Exception invoking method [%s] on object [%s], using arguments ["method.getName(), obj));
        if (args != null) {
            for (int i = 0; i < args.lengthi++) {
                message.append(i > 0 ? "," : "").append(args[i]);
            }
        }
        message.append("]");
        return message.toString();
    }
    public static void setFieldValue(Field fieldObject instanceObject value) {
        field.setAccessible(true);
        try {
            field.set(instancevalue);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(buildSetFieldValueErrorMessage(fieldinstancevalue), e);
        } catch (NullPointerException ex) {
            NullPointerException ex2 = new NullPointerException(buildSetFieldValueErrorMessage(fieldinstancevalue));
            ex2.initCause(ex.getCause());
            throw ex2;
        }
    }
    private static String buildSetFieldValueErrorMessage(Field fieldObject objObject value) {
        return String.format("Exception setting [%s] field on object [%s] to value [%s]"field.getName(), objvalue);
    }
    private static String buildGetFieldValueErrorMessage(Field fieldObject obj) {
        return String.format("Exception reading [%s] field from object [%s]."field.getName(), obj);
    }
    public static <T> T getFieldValue(Field fieldObject instanceClass<T> expectedType) {
        field.setAccessible(true);
        try {
            return expectedType.cast(field.get(instance));
        } catch (IllegalAccessException e) {
            throw new RuntimeException(buildGetFieldValueErrorMessage(fieldinstance), e);
        } catch (NullPointerException ex) {
            NullPointerException ex2 = new NullPointerException(buildGetFieldValueErrorMessage(fieldinstance));
            ex2.initCause(ex.getCause());
            throw ex2;
        }
    }
    public static ClassLoader getClassLoader() {
        final ClassLoader tccl = Thread.currentThread().getContextClassLoader();
        if (tccl != null) {
            return tccl;
        } else {
            return Reflections.class.getClassLoader();
        }
    }
New to GrepCode? Check out our FAQ X