Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  package org.deephacks.tools4j.config.internal.core;
  
  
 import java.util.List;
 import java.util.Map;

General purpose class for commonly used reflection operations.

Author(s):
Kristoffer Sjogren
 
 public class Reflections {
     public static Class<?> forName(String className) {
         try {
             return Thread.currentThread().getContextClassLoader().loadClass(className);
         } catch (ClassNotFoundException e) {
             throw new RuntimeException(e);
         }
     }

    
Get all superclasses and interfaces recursively.

Parameters:
clazz The class to start the search with.
Returns:
List of all super classes and interfaces of clazz. The list contains the class itself! The empty list is returned if clazz is null.
 
     public static List<Class<?>> computeClassHierarchy(Class<?> clazz) {
         List<Class<?>> classes = new ArrayList<Class<?>>();
         computeClassHierarchy(clazzclasses);
         return classes;
     }

    
Get all superclasses and interfaces recursively.

Parameters:
clazz The class to start the search with.
classes List of classes to which to add all found super classes and interfaces.
 
     private static void computeClassHierarchy(Class<?> clazzList<Class<?>> classes) {
         for (Class<?> current = clazzcurrent != nullcurrent = current.getSuperclass()) {
             if (classes.contains(current)) {
                 return;
             }
             classes.add(current);
             for (Class<?> currentInterface : current.getInterfaces()) {
                 computeClassHierarchy(currentInterfaceclasses);
             }
         }
     }
 
     public static List<Class<?>> computeEnclosingClasses(Class<?> clazz) {
         List<Class<?>> classes = new ArrayList<Class<?>>();
         computeEnclosingClasses(clazzclasses);
         return classes;
     }
 
     private static void computeEnclosingClasses(Class<?> clazzList<Class<?>> classes) {
         for (Class<?> current = clazzcurrent != nullcurrent = current.getEnclosingClass()) {
             if (classes.contains(current)) {
                 return;
             }
             classes.add(current);
             for (Class<?> currentInterface : current.getInterfaces()) {
                 computeEnclosingClasses(currentInterfaceclasses);
             }
         }
     }
 
     public static <T> T newInstance(Class<T> typethrows InstantiationException,
         Constructor<?> c;
         if(Modifier.isStatic(type.getModifiers())) {
             c = type.getDeclaredConstructor(new Class[] {});
         } else {
             try {
                 Class<?> enclosing = type.getEnclosingClass();
                 if(type.getName().contains("$") && enclosing != null) {
                     throw new IllegalArgumentException("Non-static inner classes are not supported: " + type);
                 }
             } catch (Exception e) {
                 // this may occur for byte code generated proxies
                 throw new IllegalArgumentException("Non-static inner classes are not supported: " + type);
            }
            c = type.getDeclaredConstructor();
        }
        c.setAccessible(true);
        return type.cast(c.newInstance());
    }
    public static Object newInstance(String clazzNameString value) {
        try {
            Class<?> type = forName(clazzName);
            Class<?> enclosing = type.getEnclosingClass();
            if (enclosing == null) {
                Constructor<?> c = type.getConstructor(String.class);
                c.setAccessible(true);
                return type.cast(c.newInstance(value));
            }
            Object o = enclosing.newInstance();
            Constructor<?> c = type.getDeclaredConstructor(enclosingString.class);
            c.setAccessible(true);
            return type.cast(c.newInstance(ovalue));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    public static Object newInstance(String className) {
        try {
            Class<?> type = forName(className);
            Class<?> enclosing = type.getEnclosingClass();
            if (enclosing == null) {
                Constructor<?> c = type.getDeclaredConstructor();
                c.setAccessible(true);
                return c.newInstance();
            }
            Object o = enclosing.newInstance();
            Constructor<?> cc = type.getDeclaredConstructor(enclosing);
            cc.setAccessible(true);
            return cc.newInstance(o);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    @SuppressWarnings("unchecked")
    public static <T> Class<? extends T> getComponentType(T[] a) {
        Class<?> k = a.getClass().getComponentType();
        return (Class<? extends T>) k// unchecked cast
    }
    public static <T> T[] newArray(T[] aint size) {
        return newArray(getComponentType(a), size);
    }
    @SuppressWarnings("unchecked")
    public static <T> T[] newArray(Class<? extends T> kint size) {
        if (k.isPrimitive())
            throw new IllegalArgumentException("Argument cannot be primitive: " + k);
        Object a = java.lang.reflect.Array.newInstance(ksize);
        return (T[]) a// unchecked cast
    }
    public static <T> T cast(Class<T> clazzObject object) {
        if (object == null) {
            return null;
        }
        if (clazz.isAssignableFrom(object.getClass())) {
            return clazz.cast(object);
        }
        return null;
    }

    
Find all field (including private) on a specific class. Searches all super-classes up to java.lang.Object. If the same field name is found in a superclass it is ignore.

Parameters:
clazz Class to inspect
Returns:
all found fields.
    public static Map<StringFieldfindFields(final Class<?> clazz) {
        Map<StringFieldfoundFields = new HashMap<>();
        Class<?> searchType = clazz;
        while (!Object.class.equals(searchType) && (searchType != null)) {
            Field[] fields = searchType.getDeclaredFields();
            for (Field field : fields) {
                field.setAccessible(true);
                if(foundFields.get(field.getName()) == null) {
                    foundFields.put(field.getName(), field);
                }
            }
            searchType = searchType.getSuperclass();
        }
        return foundFields;
    }
    public static Field findField(final Class<?> clsString fieldName) {
        Class<?> searchType = cls;
        while (!Object.class.equals(searchType) && (searchType != null)) {
            Field field = null;
            try {
                field = searchType.getDeclaredField(fieldName);
            } catch (NoSuchFieldException e) {
                // ignore
            }
            if(field != null) {
                field.setAccessible(true);
                return field;
            }
            searchType = searchType.getSuperclass();
        }
        throw new RuntimeException("Could not find field " + fieldName + " on " + cls);
    }
    public static Multimap<Class<? extends Annotation>, FieldfindFieldsAnnotations(
            List<Fieldfields) {
        Multimap<Class<? extends Annotation>, FieldfieldAnnotations = ArrayListMultimap.create();
        for (Field field : fields) {
            field.setAccessible(true);
            Annotation[] annotations = field.getAnnotations();
            for (Annotation annotation : annotations) {
                fieldAnnotations.put(annotation.annotationType(), field);
            }
        }
        return fieldAnnotations;
    }

    
Returns the parameterized type of a field, if exists. Wild cards, type variables and raw types will be returned as an empty list.

If a field is of type Set<String> then java.lang.String is returned.

If a field is of type Map<String, Integer> then [java.lang.String, java.lang.Integer] is returned.

Parameters:
field
Returns:
A list of classes of the parameterized type.
    public static List<Class<?>> getParameterizedType(final Field field) {
        Type type = field.getGenericType();
        if (!ParameterizedType.class.isAssignableFrom(type.getClass())) {
            // the field is it a raw type and does not have generic type
            // argument. Return empty list.
            return new ArrayList<Class<?>>();
        }
        ParameterizedType ptype = (ParameterizedTypetype;
        Type[] targs = ptype.getActualTypeArguments();
        List<Class<?>> classes = new ArrayList<Class<?>>();
        for (Type aType : targs) {
            if (Class.class.isAssignableFrom(aType.getClass())) {
                classes.add((Class<?>) aType);
            } else if (WildcardType.class.isAssignableFrom(aType.getClass())) {
                // wild cards are not handled by this method
            } else if (TypeVariable.class.isAssignableFrom(aType.getClass())) {
                // type variables are not handled by this method
            }
        }
        return classes;
    }

    
Returns the parameterized type of a class, if exists. Wild cards, type variables and raw types will be returned as an empty list.

If a field is of type Set<String> then java.lang.String is returned.

If a field is of type Map<String, Integer> then [java.lang.String, java.lang.Integer] is returned.

Parameters:
ownerClass the implementing target class to check against
the generic interface to resolve the type argument from
Returns:
A list of classes of the parameterized type.
    public static List<Class<?>> getParameterizedType(final Class<?> ownerClass,
            Class<?> genericSuperClass) {
        Type[] types = null;
        if (genericSuperClass.isInterface()) {
            types = ownerClass.getGenericInterfaces();
        } else {
            types = new Type[] { ownerClass.getGenericSuperclass() };
        }
        List<Class<?>> classes = new ArrayList<Class<?>>();
        for (Type type : types) {
            if (!ParameterizedType.class.isAssignableFrom(type.getClass())) {
                // the field is it a raw type and does not have generic type
                // argument. Return empty list.
                return new ArrayList<Class<?>>();
            }
            ParameterizedType ptype = (ParameterizedTypetype;
            Type[] targs = ptype.getActualTypeArguments();
            for (Type aType : targs) {
                classes.add(extractClass(ownerClassaType));
            }
        }
        return classes;
    }
    public static Method getStaticMethod(Class<?> clazzString methodNameClass<?>... args) {
        try {
            Method method = clazz.getMethod(methodNameargs);
            return Modifier.isStatic(method.getModifiers()) ? method : null;
        } catch (NoSuchMethodException ex) {
            return null;
        }
    }
    public static <T> Constructor<T> getConstructor(Class<T> clazzClass<?>... paramTypes) {
        try {
            return clazz.getConstructor(paramTypes);
        } catch (NoSuchMethodException ex) {
            return null;
        }
    }
    private static Class<?> extractClass(Class<?> ownerClassType arg) {
        if (arg instanceof ParameterizedType) {
            return extractClass(ownerClass, ((ParameterizedTypearg).getRawType());
        } else if (arg instanceof GenericArrayType) {
            throw new UnsupportedOperationException("GenericArray types are not supported.");
        } else if (arg instanceof TypeVariable) {
            throw new UnsupportedOperationException("GenericArray types are not supported.");
        }
        return (arg instanceof Class ? (Class<?>) arg : Object.class);
    }
New to GrepCode? Check out our FAQ X