Package io.microsphere.reflect
Class AccessibleObjectUtils
- java.lang.Object
-
- io.microsphere.reflect.AccessibleObjectUtils
-
-
Method Summary
All Methods Static Methods Concrete Methods Modifier and Type Method Description static booleancanAccess(java.lang.Object object, java.lang.reflect.AccessibleObject accessibleObject)Tests whether the caller can access the specifiedAccessibleObjectwith the given instance.static booleantrySetAccessible(java.lang.reflect.AccessibleObject accessibleObject)Attempts to set the accessibility of the givenAccessibleObject.
-
-
-
Method Detail
-
trySetAccessible
public static boolean trySetAccessible(java.lang.reflect.AccessibleObject accessibleObject)
Attempts to set the accessibility of the givenAccessibleObject.This method intelligently selects the appropriate approach based on the JDK version:
- If running on JDK 9 or later, it uses the
AccessibleObject#trySetAccessible()method via aMethodHandle. - If running on JDK 8 or earlier, it falls back to calling the traditional
AccessibleObject.setAccessible(boolean)method, but only if it is not already accessible.
Example Usage
Field field = MyClass.class.getDeclaredField("myField"); boolean success = AccessibleObjectUtils.trySetAccessible(field); if (success) { // Access the field reflectively }- Parameters:
accessibleObject- TheAccessibleObjectinstance to make accessible.- Returns:
trueif the object was successfully made accessible;falseotherwise.- See Also:
AccessibleObject#trySetAccessible(),AccessibleObject.setAccessible(boolean),AccessibleObject.isAccessible()
- If running on JDK 9 or later, it uses the
-
canAccess
public static boolean canAccess(java.lang.Object object, java.lang.reflect.AccessibleObject accessibleObject)Tests whether the caller can access the specifiedAccessibleObjectwith the given instance.If the reflected object corresponds to an instance method or field, the provided
objectmust be an instance of the declaring class. For static members and constructors, theobjectmust benull.Example Usage
Testing Access to an Instance Field
MyClass instance = new MyClass(); Field field = MyClass.class.getDeclaredField("myField"); boolean accessible = AccessibleObjectUtils.canAccess(instance, field); if (accessible) { System.out.println("Field is accessible."); }Testing Access to a Static Method
Method method = MyClass.class.getDeclaredMethod("myStaticMethod"); boolean accessible = AccessibleObjectUtils.canAccess(null, method); if (accessible) { System.out.println("Static method is accessible."); }- Parameters:
object- An instance of the declaring class for instance methods/fields; must benullfor static members or constructors.accessibleObject- The reflected object (field, method, constructor) to test access for.- Returns:
trueif the caller can access this reflected object;falseotherwise.- See Also:
AccessibleObject.isAccessible()
-
-