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 boolean
canAccess(java.lang.Object object, java.lang.reflect.AccessibleObject accessibleObject)
Tests whether the caller can access the specifiedAccessibleObject
with the given instance.static boolean
trySetAccessible(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
- TheAccessibleObject
instance to make accessible.- Returns:
true
if the object was successfully made accessible;false
otherwise.- 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 specifiedAccessibleObject
with the given instance.If the reflected object corresponds to an instance method or field, the provided
object
must be an instance of the declaring class. For static members and constructors, theobject
must 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 benull
for static members or constructors.accessibleObject
- The reflected object (field, method, constructor) to test access for.- Returns:
true
if the caller can access this reflected object;false
otherwise.- See Also:
AccessibleObject.isAccessible()
-
-