Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  package org.infinispan.commons.util;
  
  
 import java.util.List;
Basic reflection utilities to enhance what the JDK provides.

Author(s):
Manik Surtani (manik@jboss.org)
Since:
4.0
 
 public class ReflectionUtil {
    private static final Log log = LogFactory.getLog(ReflectionUtil.class);
 
    private static final String[] EMPTY_STRING_ARRAY = {};
 
    private static final Class<?>[] primitives = {int.classbyte.classshort.classlong.class,
                                                  float.classdouble.classboolean.classchar.class};
 
    private static final Class<?>[] primitiveArrays = {int[].classbyte[].classshort[].classlong[].class,
                                                       float[].classdouble[].classboolean[].classchar[].class};
    public static final Class<?>[] EMPTY_CLASS_ARRAY = new Class[0];


   
Returns a set of Methods that contain the given method annotation. This includes all public, protected, package and private methods, as well as those of superclasses. Note that this does *not* include overridden methods.

Parameters:
c class to inspect
annotationType the type of annotation to look for
Returns:
List of Method objects that require injection.
 
    public static List<MethodgetAllMethods(Class<?> cClass<? extends AnnotationannotationType) {
       List<Methodannotated = new LinkedList<Method>();
       inspectRecursively(cannotatedannotationType);
       return annotated;
    }

   
Returns a set of Methods that contain the given method annotation. This includes all public, protected, package and private methods, but not those of superclasses and interfaces.

Parameters:
c class to inspect
annotationType the type of annotation to look for
Returns:
List of Method objects that require injection.
 
    public static List<MethodgetAllMethodsShallow(Class<?> cClass<? extends AnnotationannotationType) {
       List<Methodannotated = new LinkedList<Method>();
       for (Method m : c.getDeclaredMethods()) {
          if (m.isAnnotationPresent(annotationType))
             annotated.add(m);
       }
 
       return annotated;
    }
 
    private static void getAnnotatedFieldHelper(List<FieldlistClass<?> cClass<? extends AnnotationannotationType) {
       Field[] declaredFields = c.getDeclaredFields();
       for (Field field : declaredFields) {
          if (field.isAnnotationPresent(annotationType)) {
             list.add(field);
          }
       }
    }
 
    public static List<FieldgetAnnotatedFields(Class<?> cClass<? extends AnnotationannotationType) {
       List<Fieldfields = new ArrayList<Field>(4);
       // Class could be null in the case of an interface
       for (;c != null && !c.equals(Object.class); c = c.getSuperclass()) {
          getAnnotatedFieldHelper(fieldscannotationType);
       }
       return fields;
    }
 
    public static Method findMethod(Class<?> typeString methodName) {
       try {
          return type.getDeclaredMethod(methodName);
       } catch (NoSuchMethodException e) {
          if (type.equals(Object.class) || type.isInterface()) {
             throw new CacheException(e);
          }
          return findMethod(type.getSuperclass(), methodName);
       }
    }
 
    public static Method findMethod(Class<?> typeString methodNameClass<?>[] parametersthrows ClassNotFoundException {
      try {
         return type.getDeclaredMethod(methodNameparameters);
      } catch (NoSuchMethodException e) {
         if (type.equals(Object.class) || type.isInterface()) {
            throw new CacheException(e);
         }
         return findMethod(type.getSuperclass(), methodNameparameters);
      }
   }

   
Inspects a class and its superclasses (all the way to java.lang.Object for method instances that contain a given annotation. This even identifies private, package and protected methods, not just public ones.

Parameters:
c
s
annotationType
   private static void inspectRecursively(Class<?> cList<MethodsClass<? extends AnnotationannotationType) {
      for (Method m : c.getDeclaredMethods()) {
         // don't bother if this method has already been overridden by a subclass
         if (notFound(ms) && m.isAnnotationPresent(annotationType)) {
            s.add(m);
         }
      }
      if (!c.equals(Object.class)) {
         if (!c.isInterface()) {
            inspectRecursively(c.getSuperclass(), sannotationType);
            for (Class<?> ifc : c.getInterfaces()) inspectRecursively(ifcsannotationType);
         }
      }
   }

   
Tests whether a method has already been found, i.e., overridden.

Parameters:
m method to inspect
s collection of methods found
Returns:
true a method with the same signature already exists.
   private static boolean notFound(Method mCollection<Methods) {
      for (Method found : s) {
         if (m.getName().equals(found.getName()) &&
               Arrays.equals(m.getParameterTypes(), found.getParameterTypes()))
            return false;
      }
      return true;
   }
   public static void setValue(Object instanceString fieldNameObject value) {
      try {
         Field f = findFieldRecursively(instance.getClass(), fieldName);
         if (f == null)
            throw new NoSuchMethodException("Cannot find field " + fieldName + " on " + instance.getClass() + " or superclasses");
         f.setAccessible(true);
         f.set(instancevalue);
      } catch (Exception e) {
         .unableToSetValue(e);
      }
   }
   private static Field findFieldRecursively(Class<?> cString fieldName) {
      Field f = null;
      try {
         f = c.getDeclaredField(fieldName);
      } catch (NoSuchFieldException e) {
         if (!c.equals(Object.class)) f = findFieldRecursively(c.getSuperclass(), fieldName);
      }
      return f;
   }

   
Invokes a method using reflection, in an accessible manner (by using java.lang.reflect.AccessibleObject.setAccessible(boolean)

Parameters:
instance instance on which to execute the method
method method to execute
parameters parameters
   public static Object invokeAccessibly(Object instanceMethod methodObject[] parameters) {
      try {
         method.setAccessible(true);
         return method.invoke(instanceparameters);
      } catch (InvocationTargetException e) {
         throw new CacheException("Unable to invoke method " + method + " on object of type " + (instance == null ? "null" : instance.getClass().getSimpleName()) +
                                        (parameters != null ? " with parameters " + Arrays.asList(parameters) : ""), e.getCause());
      } catch (Exception e) {
         throw new CacheException("Unable to invoke method " + method + " on object of type " + (instance == null ? "null" : instance.getClass().getSimpleName()) +
               (parameters != null ? " with parameters " + Arrays.asList(parameters) : ""), e);
      }
   }
   public static Method findGetterForField(Class<?> cString fieldName) {
      Method retval = findGetterForFieldUsingReflection(cfieldName);
      if (retval == null) {
         if (!c.equals(Object.class)) {
            if (!c.isInterface()) {
               retval = findGetterForField(c.getSuperclass(), fieldName);
               if (retval == null) {
                  for (Class<?> ifc : c.getInterfaces()) {
                     retval = findGetterForField(ifcfieldName);
                     if (retval != nullbreak;
                  }
               }
            }
         }
      }
      return retval;
   }
   private static Method findGetterForFieldUsingReflection(Class<?> cString fieldName) {
      for (Method m : c.getDeclaredMethods()) {
         String name = m.getName();
         String s = null;
         if (name.startsWith("get")) {
            s = name.substring(3);
         } else if (name.startsWith("is")) {
            s = name.substring(2);
         }
         if (s != null && s.equalsIgnoreCase(fieldName)) {
            return m;
         }
      }
      return null;
   }
   public static Method findSetterForField(Class<?> cString fieldName) {
      for (Method m : c.getDeclaredMethods()) {
         String name = m.getName();
         String s = null;
         if (name.startsWith("set")) {
            s = name.substring(3);
         }
         if (s != null && s.equalsIgnoreCase(fieldName)) {
            return m;
         }
      }
      return null;
   }
   public static String extractFieldName(String setterOrGetter) {
      String field = null;
      if (setterOrGetter.startsWith("set") || setterOrGetter.startsWith("get"))
         field = setterOrGetter.substring(3);
      else if (setterOrGetter.startsWith("is"))
         field = setterOrGetter.substring(2);
      if (field != null && field.length() > 1) {
         StringBuilder sb = new StringBuilder();
         sb.append(Character.toLowerCase(field.charAt(0)));
         if (field.length() > 2) sb.append(field.substring(1));
         return sb.toString();
      }
      return null;
   }


   
Retrieves the value of a field of an object instance via reflection

Parameters:
instance to inspect
fieldName name of field to retrieve
Returns:
a value
   public static Object getValue(Object instanceString fieldName) {
      Field f = findFieldRecursively(instance.getClass(), fieldName);
      if (f == nullthrow new CacheException("Could not find field named '" + fieldName + "' on instance " + instance);
      try {
         f.setAccessible(true);
         return f.get(instance);
      } catch (IllegalAccessException iae) {
         throw new CacheException("Cannot access field " + fiae);
      }
   }

   
Inspects the class passed in for the class level annotation specified. If the annotation is not available, this method recursively inspects superclasses and interfaces until it finds the required annotation.

Returns null if the annotation cannot be found.

Parameters:
clazz class to inspect
ann annotation to search for. Must be a class-level annotation.
Returns:
the annotation instance, or null
   @SuppressWarnings("unchecked")
   public static <T extends Annotation> T getAnnotation(Class<?> clazzClass<T> ann) {
      while (true) {
         // first check class
         T a = clazz.getAnnotation(ann);
         if (a != nullreturn a;
         // check interfaces
         if (!clazz.isInterface()) {
            Class<?>[] interfaces = clazz.getInterfaces();
            for (Class<?> inter : interfaces) {
               a = getAnnotation(interann);
               if (a != nullreturn a;
            }
         }
         // check superclasses
         Class<?> superclass = clazz.getSuperclass();
         if (superclass == nullreturn null// no where else to look
         clazz = superclass;
      }
   }

   
Tests whether an annotation is present on a class. The order tested is:
  • The class itself
  • All implemented interfaces
  • Any superclasses

Parameters:
clazz class to test
annotation annotation to look for
Returns:
true if the annotation is found, false otherwise
   public static boolean isAnnotationPresent(Class<?> clazzClass<? extends Annotationannotation) {
      return getAnnotation(clazzannotation) != null;
   }
   public static Class<?>[] toClassArray(String[] typeListClassLoader classLoaderthrows ClassNotFoundException {
      if (typeList == nullreturn ;
      Class<?>[] retval = new Class[typeList.length];
      int i = 0;
      for (String s : typeListretval[i++] = getClassForName(sclassLoader);
      return retval;
   }
   public static Class<?> getClassForName(String nameClassLoader clthrows ClassNotFoundException {
      try {
         return Util.loadClassStrict(namecl);
      } catch (ClassNotFoundException cnfe) {
         // Could be a primitive - let's check
         for (Class<?> primitive : if (name.equals(primitive.getName())) return primitive;
         for (Class<?> primitive : if (name.equals(primitive.getName())) return primitive;
      }
      throw new ClassNotFoundException("Class " + name + " cannot be found");
   }
   public static String[] toStringArray(Class<?>[] classes) {
      if (classes == null)
         return ;
      else {
         String[] classNames = new String[classes.length];
         for (int i=0; i<classes.lengthi++) classNames[i] = classes[i].getName();
         return classNames;
      }
   }
   public static Field getField(String fieldNameClass<?> objectClass) {
      try {
         return objectClass.getDeclaredField(fieldName);
      } catch (NoSuchFieldException e) {
         if (!objectClass.equals(Object.class)) {
            return getField(fieldNameobjectClass.getSuperclass());
         } else {
            return null;
         }
      }
   }
   public static void applyProperties(Object oProperties p) {
      for(Entry<ObjectObjectentry : p.entrySet()) {
         setValue(o, (Stringentry.getKey(), entry.getValue());
      }
   }
   public static <T> T unwrap(Object objClass<T> clazz) {
      if (clazz != null && clazz.isAssignableFrom(obj.getClass()))
         return clazz.cast(obj);
      throw .unableToUnwrap(objclazz);
   }
New to GrepCode? Check out our FAQ X