Top Reflection Utility Methods

In this article, we will learn useful reflection utility methods. You can use these Reflection utility methods in your day to day project work. This post provides a list of 25 useful and commonly used reflection utility methods.
These Reflection Utility methods static methods and generic methods and probably these methods may help you to understand Java Reflection concepts.

Don't forget to check out: Java Reflection Utility Class

1. Find Field

This method is used to find a Field on the supplied Class with the supplied name. Searches all superclasses up to Object.
public static Field findField(Class << ? > clazz, String name) {
    Class << ? > searchType = clazz;
    while (Object.class != searchType && searchType != null) {
        Field[] fields = searchType.getDeclaredFields();
        for (Field field: fields) {
            if ((name == null || name.equals(field.getName()))) {
                return field;
            }
        }
        searchType = searchType.getSuperclass();
    }
    return null;
}

2. Set Field

Set the field represented by the supplied Field field object on the specified Object target object to the specified value.
public static void setField(Field field, Object target, Object value) {
    try {
        field.set(target, value);
    } catch (IllegalAccessException ex) {
         throw new IllegalStateException(
             "Unexpected reflection exception - " + ex.getClass().getName() + ": " + ex.getMessage());
    }
}

3. Get Field

Get the field represented by the supplied Field field object on the specified Object target object.
public static Object getField(Field field, Object target) {
    try {
         return field.get(target);
    } catch (IllegalAccessException ex) {
         throw new IllegalStateException(
             "Unexpected reflection exception - " + ex.getClass().getName() + ": " + ex.getMessage());
    }
}

4. Make the Given Field Accessible

Make the given field accessible, explicitly setting it accessible if necessary.
public static void makeAccessible(Field field) {
       if ((!Modifier.isPublic(field.getModifiers()) 
                        || !Modifier.isPublic(field.getDeclaringClass().getModifiers())
         || Modifier.isFinal(field.getModifiers())) && !field.isAccessible()) {
        field.setAccessible(true);
    }
}

5. Check Field "public static final" constant

Determine whether the given field is a "public static final" constant.
public static boolean isPublicStaticFinal(Field field) {
    int modifiers = field.getModifiers();
    return (Modifier.isPublic(modifiers) && Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers));
}

6. Get Fields Including Super Classes

public static List < Field > getFieldsIncludingSuperclasses(Class << ? > clazz) {
    List < Field > fields = new ArrayList < Field > (Arrays.asList(clazz.getDeclaredFields()));

    Class << ? > superclass = clazz.getSuperclass();

    if (superclass != null) {
        fields.addAll(getFieldsIncludingSuperclasses(superclass));
    }

    return fields;
}

7. Find Method

find a Method on the supplied class with the supplied name and no parameters. Searches all superclasses up to Object.
public static Method findMethod(Class<?> clazz, String name) {
    Class<?> searchType = clazz;
    while (searchType != null) {
         Method[] methods = (searchType.isInterface() ? searchType.getMethods() : searchType.getDeclaredMethods());
         for (Method method : methods) {
             if (name.equals(method.getName())) {
                  return method;
             }
         }
        searchType = searchType.getSuperclass();
    }
    return null;
}

8. Invoke the specified Method

Invoke the specified Method against the supplied target object with the supplied arguments. The target object can be null when invoking a static Method.
public static Object invokeMethod(Method method, Object target, Object... args) {
    try {
         return method.invoke(target, args);
    } catch (Exception ex) {
         handleReflectionException(ex);
    }
    throw new IllegalStateException("Should never get here");
}

9. Check method is an "equals" method

Determine whether the given method is an "equals" method.
public static boolean isEqualsMethod(Method method) {
    if (method == null || !method.getName().equals("equals")) {
         return false;
    }
    Class<?>[] paramTypes = method.getParameterTypes();
    return (paramTypes.length == 1 && paramTypes[0] == Object.class);
}

10. Check method is a "hashCode" method

Determine whether the given method is a "hashCode" method.
public static boolean isHashCodeMethod(Method method) {
    return (method != null && method.getName().equals("hashCode") 
               && method.getParameterCount() == 0);
}

11. Check method is a "toString" method

Determine whether the given method is a "toString" method.
public static boolean isToStringMethod(Method method) {
    return (method != null && method.getName().equals("toString") 
               && method.getParameterCount() == 0);
}

12. Make the Given Method Accessible

Make the given method accessible, explicitly setting it accessible if necessary.
public static void makeAccessible(Method method) {
    if ((!Modifier.isPublic(method.getModifiers()) 
        || !Modifier.isPublic(method.getDeclaringClass().getModifiers()))
         && !method.isAccessible()) {
        method.setAccessible(true);
    }
}

13. Get All Setter Methods

Finds all setters in the given class and superclasses.
public static List<Method> getSetters(Class<?> clazz) {
    Method[] methods = clazz.getMethods();

    List<Method> list = new ArrayList<Method>();

    for (Method method : methods) {
         if (isSetter(method)) {
             list.add(method);
         }
    }

    return list;
}

public static boolean isSetter(Method method) {
    return method.getReturnType().equals(Void.TYPE) && 
        !Modifier.isStatic(method.getModifiers()) && 
        method.getParameterTypes().length == 1;
}

14. Check if Class is Public

public static boolean isPublic(Class<?> clazz) {
    return Modifier.isPublic(clazz.getModifiers());
}

15. Check if Method or Field or Constructor is Public

Member is an interface that reflects identifying information about a single member (a field or a method) or a constructor.
public static boolean isPublic(Member member) {
    return Modifier.isPublic(member.getModifiers());
}

16. Check If Class is Private

public static boolean isPrivate(Class<?> clazz) {
    return Modifier.isPrivate(clazz.getModifiers());
}

17. Check If Method or Field or Constructor is Private

public static boolean isPrivate(Member member) {
    return Modifier.isPrivate(member.getModifiers());
}

18. Check if Method or Field or Constructor is not Private

public static boolean isNotPrivate(Member member) {
    return !isPrivate(member);
}

19. Check if the Class is Abstract

public static boolean isAbstract(Class<?> clazz) {
    return Modifier.isAbstract(clazz.getModifiers());
}

20. Check if Method or Field or Constructor Abstract

public static boolean isAbstract(Member member) {
    return Modifier.isAbstract(member.getModifiers());
}

21. Check if the Class is Static

public static boolean isStatic(Class<?> clazz) {
    return Modifier.isStatic(clazz.getModifiers());
}

22. Check if Method or Field or Constructor are static

public static boolean isStatic(Member member) {
    return Modifier.isStatic(member.getModifiers());
}

23. Check if the Class is Inner Class

Determine if the supplied class is an inner class.
public static boolean isInnerClass(Class<?> clazz) {
    return !isStatic(clazz) && clazz.isMemberClass();
}

24. Check if the Object is an Array

Determine if the supplied object is an array.
public static boolean isArray(Object obj) {
    return (obj != null && obj.getClass().isArray());
}

25. Make the Given Constructor Accessible

Make the given constructor accessible, explicitly setting it accessible if necessary.
public static void makeAccessible(Constructor<?> ctor) {
    if ((!Modifier.isPublic(ctor.getModifiers()) 
        || !Modifier.isPublic(ctor.getDeclaringClass().getModifiers()))
      && !ctor.isAccessible()) {
     ctor.setAccessible(true);
    }
}

Related Posts

Comments