Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * Copyright (C) 2011 the original author or authors.
   *
   * 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.codehaus.gmavenplus.util;
 
Inspired by Spring's ReflectionUtils.

Author(s):
Keegan Witt
Since:
1.0-beta-1
 
 public class ReflectionUtils {

    
Private constructor that should never be called since this is a static utility class.
 
     private ReflectionUtils() { }

    
Attempt to find a java.lang.reflect.Method on the supplied class with the supplied name and parameter types. Searches all superclasses up to Object.

Parameters:
clazz The class to introspect
name The name of the method
paramTypes The parameter types of the method (may be null to indicate any signature)
Returns:
The Method object
 
     public static Method findMethod(final Class<?> clazzfinal String namefinal Class<?>... paramTypes) {
         if (clazz == null) {
             throw new IllegalArgumentException("Class must not be null.");
         }
         if (name == null) {
             throw new IllegalArgumentException("Method name must not be null.");
         }
         Class<?> searchType = clazz;
         while (searchType != null) {
             Method[] methods = searchType.isInterface() ? searchType.getMethods() : searchType.getDeclaredMethods();
             for (Method method : methods) {
                 if (name.equals(method.getName()) && (paramTypes == null || Arrays.equals(paramTypesmethod.getParameterTypes()))) {
                     return method;
                 }
             }
             searchType = searchType.getSuperclass();
         }
         throw new IllegalArgumentException("Unable to find method " + clazz.getName() + "." + name + "(" + Arrays.toString(paramTypes).replaceAll("^\\[""").replaceAll("\\]$""").replaceAll("class """) + ").");
     }

    
Attempt to find a java.lang.reflect.Constructor on the supplied class with the supplied parameter types. Searches all superclasses up to Object.

Parameters:
clazz The class to introspect
paramTypes The parameter types of the method (may be null to indicate any signature)
Returns:
The Constructor object
 
     public static Constructor findConstructor(final Class<?> clazzfinal Class<?>... paramTypes) {
         if (clazz == null) {
             throw new IllegalArgumentException("Class must not be null.");
         }
         Class<?> searchType = clazz;
         while (searchType != null) {
             Constructor[] constructors = searchType.isInterface() ? searchType.getConstructors() : searchType.getDeclaredConstructors();
             for (Constructor constructor : constructors) {
                 if (paramTypes == null || Arrays.equals(paramTypesconstructor.getParameterTypes())) {
                     return constructor;
                 }
             }
             searchType = searchType.getSuperclass();
         }
         throw new IllegalArgumentException("Unable to find constructor " + clazz.getName() + "(" + Arrays.toString(paramTypes).replaceAll("^\\[""").replaceAll("\\]$""").replaceAll("class """) + ").");
     }

    
Invoke the specified java.lang.reflect.Method against the supplied target object with the supplied arguments. The target object can be null when invoking a static java.lang.reflect.Method.

Parameters:
method The method to invoke
target The target object to invoke the method on
args The invocation arguments (may be null)
Returns:
The invocation result, if any
Throws:
java.lang.IllegalAccessException when unable to access the specified method because access modifiers prevent it
java.lang.reflect.InvocationTargetException when a reflection invocation fails
    public static Object invokeMethod(final Method methodfinal Object targetfinal Object... argsthrows InvocationTargetExceptionIllegalAccessException {
        if (method == null) {
            throw new IllegalArgumentException("Method must not be null.");
        }
        if (target == null) {
            throw new IllegalArgumentException("Object must not be null.");
        }
        method.setAccessible(true);
        return method.invoke(targetargs);
    }

    
Invoke the specified static java.lang.reflect.Method with the supplied arguments.

Parameters:
method The method to invoke
args The invocation arguments (may be null)
Returns:
The invocation result, if any
Throws:
java.lang.IllegalAccessException when unable to access the specified method because access modifiers prevent it
java.lang.reflect.InvocationTargetException when a reflection invocation fails
    public static Object invokeStaticMethod(final Method methodfinal Object... argsthrows InvocationTargetExceptionIllegalAccessException {
        if (method == null) {
            throw new IllegalArgumentException("Method must not be null.");
        }
        if (!Modifier.isStatic(method.getModifiers())) {
            throw new IllegalArgumentException("Method must be static.");
        }
        method.setAccessible(true);
        return method.invoke(nullargs);
    }

    
Invoke the specified java.lang.reflect.Constructor with the supplied arguments.

Parameters:
constructor The method to invoke
args The invocation arguments (may be null)
Returns:
The invocation result, if any
Throws:
java.lang.IllegalAccessException when unable to access the specified constructor because access modifiers prevent it
java.lang.reflect.InvocationTargetException when a reflection invocation fails
java.lang.InstantiationException when an instantiation fails
    public static Object invokeConstructor(final Constructor constructorfinal Object... argsthrows InvocationTargetExceptionIllegalAccessExceptionInstantiationException {
        if (constructor == null) {
            throw new IllegalArgumentException("Constructor must not be null.");
        }
        constructor.setAccessible(true);
        return constructor.newInstance(args);
    }

    
Attempt to find a field on the supplied java.lang.Class with the supplied name and/or type. Searches all superclasses up to java.lang.Object.

Parameters:
clazz The class to introspect
name The name of the field (may be null if type is specified)
type The type of the field (may be null if name is specified)
Returns:
The corresponding Field object
    public static Field findField(final Class<?> clazzfinal String namefinal Class<?> type) {
        if (clazz == null) {
            throw new IllegalArgumentException("Class must not be null");
        }
        if (name == null && type == null) {
            throw new IllegalArgumentException("Either name or type of the field must be specified.");
        }
        Class<?> searchType = clazz;
        while (!Object.class.equals(searchType) && searchType != null) {
            Field[] fields = searchType.getDeclaredFields();
            for (Field field : fields) {
                if ((name == null || name.equals(field.getName())) && (type == null || type.equals(field.getType()))) {
                    return field;
                }
            }
            searchType = searchType.getSuperclass();
        }
        throw new IllegalArgumentException("Unable to find " + (type != null ? type.getName() : "") + " " + (name != null ? name : "") + ".");
    }

    
Get the field represented by the supplied field object on the specified target object. In accordance with java.lang.reflect.Field.get(java.lang.Object) semantics, the returned value is automatically wrapped if the underlying field has a primitive type.

Parameters:
field The field to get
target The target object from which to get the field
Returns:
The field's current value
Throws:
java.lang.IllegalAccessException when unable to access the specified field because access modifiers prevent it
    public static Object getField(final Field fieldfinal Object targetthrows IllegalAccessException {
        field.setAccessible(true);
        return field.get(target);
    }

    
Get the field represented by the supplied field object on the specified target object. In accordance with java.lang.reflect.Field.get(java.lang.Object) semantics, the returned value is automatically wrapped if the underlying field has a primitive type.

Parameters:
field The field to get
Returns:
The field's current value
Throws:
java.lang.IllegalAccessException when unable to access the specified field because access modifiers prevent it
    public static Object getStaticField(final Field fieldthrows IllegalAccessException {
        if (!Modifier.isStatic(field.getModifiers())) {
            throw new IllegalArgumentException("Field must be static.");
        }
        return getField(fieldnull);
    }

    
Find and return the specified value from the specified enum class.

Parameters:
clazz The enum class to introspect
valueName The name of the enum value to get
Returns:
The enum value
    public static Object getEnumValue(final Class<?> clazzfinal String valueName) {
        if (clazz.isEnum()) {
            for (Object o : clazz.getEnumConstants()) {
              if (o.toString().equals(valueName)) {
                  return o;
              }
            }
            throw new IllegalArgumentException("Unable to get an enum constant with that name.");
        } else {
            throw new IllegalArgumentException(clazz + " must be an enum.");
        }
    }
New to GrepCode? Check out our FAQ X