Class ReflectionUtils

    • Method Summary

      All Methods Static Methods Concrete Methods 
      Modifier and Type Method Description
      static java.lang.Class<?> getCallerClass()
      Gets the Class of the method caller.
      static java.lang.Class<?> getCallerClass​(int invocationFrame)
      Retrieves the class of the caller at the specified invocation frame.
      static java.lang.String getCallerClassName()
      Retrieves the fully qualified name of the class that called the method invoking this method.
      static boolean isInaccessibleObjectException​(java.lang.Throwable failure)
      Checks whether the specified Throwable is an instance of java.lang.reflect.InaccessibleObjectException.
      static boolean isSupportedSunReflectReflection()
      Checks if the sun.reflect.Reflection class is available and supported in the current JVM.
      static java.util.Map<java.lang.String,​java.lang.Object> readFieldsAsMap​(java.lang.Object object)
      Reads all non-static fields of the given object and returns them as a map.
      static <T> java.util.List<T> toList​(java.lang.Object array)
      Converts an array object into a List.
      • Methods inherited from class java.lang.Object

        clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
    • Field Detail

      • SUN_REFLECT_REFLECTION_CLASS_NAME

        public static final java.lang.String SUN_REFLECT_REFLECTION_CLASS_NAME
        Sun JDK implementation class: full name of sun.reflect.Reflection
        See Also:
        Constant Field Values
      • INACCESSIBLE_OBJECT_EXCEPTION_CLASS_NAME

        public static final java.lang.String INACCESSIBLE_OBJECT_EXCEPTION_CLASS_NAME
        The class name of java.lang.reflect.InaccessibleObjectException since JDK 9
        See Also:
        Constant Field Values
      • INACCESSIBLE_OBJECT_EXCEPTION_CLASS

        @Nullable
        public static final java.lang.Class<? extends java.lang.Throwable> INACCESSIBLE_OBJECT_EXCEPTION_CLASS
        The class of java.lang.reflect.InaccessibleObjectException since JDK 9. It may be null if the JDK version is less than 9.
    • Method Detail

      • isSupportedSunReflectReflection

        public static boolean isSupportedSunReflectReflection()
        Checks if the sun.reflect.Reflection class is available and supported in the current JVM.

        This method determines whether the internal Sun JDK class sun.reflect.Reflection can be used to retrieve caller class information. This class and its methods are specific to the Sun/HotSpot JVM and may not be present or functional on other JVM implementations.

        Usage Example

        
         if (ReflectionUtils.isSupportedSunReflectReflection()) {
             System.out.println("sun.reflect.Reflection is supported.");
         } else {
             System.out.println("sun.reflect.Reflection is NOT supported.");
         }
         
        Returns:
        true if the current JVM supports the sun.reflect.Reflection class; false otherwise.
      • getCallerClassName

        @Nonnull
        public static java.lang.String getCallerClassName()
        Retrieves the fully qualified name of the class that called the method invoking this method.

        This method attempts to use the internal Sun JDK class sun.reflect.Reflection for high-performance caller class detection if available. If not supported (e.g., non-Sun/HotSpot JVM), it falls back to using the StackTraceElement approach.

        Usage Example

        
         public class Example {
             public void exampleMethod() {
                 String callerClassName = ReflectionUtils.getCallerClassName();
                 System.out.println("Caller class: " + callerClassName);
             }
         }
         

        Performance Consideration

        On Sun/HotSpot JVMs, this method is highly efficient as it leverages internal JVM mechanisms. On other JVMs, a stack trace-based approach is used, which may be less performant but ensures compatibility.

        Returns:
        The fully qualified name of the caller class.
        Throws:
        java.lang.IllegalStateException - if an error occurs while determining the caller class.
      • getCallerClass

        @Nonnull
        public static java.lang.Class<?> getCallerClass()
                                                 throws java.lang.IllegalStateException
        Gets the Class of the method caller.

        This method attempts to retrieve the calling class using the sun.reflect.Reflection class if supported by the current JVM. If not supported (e.g., non-Sun/HotSpot JVM), it falls back to using the StackTraceElement approach.

        Example Usage

        
         public class Example {
             public void testMethod() {
                 Class<?> callerClass = ReflectionUtils.getCallerClass();
                 System.out.println("Caller class: " + callerClass.getName());
             }
         }
         
        Returns:
        The Class of the method caller.
        Throws:
        java.lang.IllegalStateException - if an error occurs while trying to determine the caller class via reflection.
      • getCallerClass

        public static java.lang.Class<?> getCallerClass​(int invocationFrame)
        Retrieves the class of the caller at the specified invocation frame.

        This method attempts to use the internal Sun JDK class sun.reflect.Reflection for high-performance caller class detection if available and supported. If not supported (e.g., non-Sun/HotSpot JVM), it falls back to using the StackTraceElement approach.

        Usage Example

        
         public class Example {
             public void exampleMethod() {
                 Class<?> callerClass = ReflectionUtils.getCallerClass(2);
                 System.out.println("Caller class: " + callerClass.getName());
             }
         }
         
        Parameters:
        invocationFrame - The depth in the call stack to retrieve the caller class from. A value of 0 typically represents the immediate caller, but this may vary depending on the JVM implementation and call context.
        Returns:
        The class of the caller at the specified invocation frame.
        Throws:
        java.lang.IllegalStateException - if an error occurs while determining the caller class.
      • toList

        @Nonnull
        public static <T> java.util.List<T> toList​(java.lang.Object array)
                                            throws java.lang.IllegalArgumentException
        Converts an array object into a List.

        This method is useful for converting any array type (including nested arrays) into a list structure. If the array contains nested arrays, they will be recursively converted into lists as well.

        Usage Example

        
         String[] stringArray = {"apple", "banana", "cherry"};
         List<String> stringList = ReflectionUtils.toList(stringArray);
         System.out.println(stringList);  // Output: [apple, banana, cherry]
        
         Integer[][] nestedArray = {{1, 2}, {3, 4}};
         List<List<Integer>> nestedList = ReflectionUtils.toList(nestedArray);
         System.out.println(nestedList);  // Output: [[1, 2], [3, 4]]
         
        Parameters:
        array - The array object to convert. Must be a valid Java array.
        Returns:
        A list representation of the provided array.
        Throws:
        java.lang.IllegalArgumentException - if the input is not a valid array object.
      • readFieldsAsMap

        @Nonnull
        public static java.util.Map<java.lang.String,​java.lang.Object> readFieldsAsMap​(java.lang.Object object)
        Reads all non-static fields of the given object and returns them as a map.

        This method recursively processes nested objects, converting them into maps as well, provided they are not primitive or simple types (e.g., String, Number).

        Example Usage

        
         class Person {
             private String name;
             private int age;
             private Address address; // Assume Address is another POJO class
        
             // constructor, getters, setters...
         }
        
         class Address {
             private String city;
             private String street;
        
             // constructor, getters, setters...
         }
        
         Person person = new Person("John", 30, new Address("New York", "5th Avenue"));
         Map<String, Object> result = ReflectionUtils.readFieldsAsMap(person);
        
         // Sample output:
         // {
         //   "name": "John",
         //   "age": 30,
         //   "address": {
         //     "city": "New York",
         //     "street": "5th Avenue"
         //   }
         // }
         
        Parameters:
        object - The object whose fields are to be read.
        Returns:
        A map containing field names as keys and their corresponding values. Nested objects are also converted to maps.
        Throws:
        java.lang.IllegalStateException - if any field cannot be accessed due to security restrictions.
      • isInaccessibleObjectException

        public static boolean isInaccessibleObjectException​(java.lang.Throwable failure)
        Checks whether the specified Throwable is an instance of java.lang.reflect.InaccessibleObjectException.

        This method is useful when dealing with reflection operations that may fail due to module system restrictions introduced in JDK 9+. It avoids direct dependency on the presence of the class, which may not be available in earlier JDK versions.

        Example Usage

        
         try {
             Field field = MyClass.class.getDeclaredField("myField");
             field.setAccessible(true); // This might throw InaccessibleObjectException
         } catch (Throwable t) {
             if (ReflectionUtils.isInaccessibleObjectException(t)) {
                 System.err.println("Caught InaccessibleObjectException: " + t.getMessage());
             } else {
                 throw new RuntimeException("Unexpected error", t);
             }
         }
         
        Parameters:
        failure - The Throwable to check.
        Returns:
        true if the specified Throwable is an instance of java.lang.reflect.InaccessibleObjectException, false otherwise.