Code Snippet

Just another Code Snippet site

[Java/Reflection] Access private fields/methods

Set private attribute value :

// Update Field value
Field field = <target_class>.class.getDeclaredField("FIELDNAME");
field.setAccessible(true);
field.set(TARGET_OBJECT, NEW_VALUE);

Invoke private method :

// Call private method
Method method = CLASS_NAME.class.getDeclaredMethod("METHOD_NAME", Argument1.class, Argument2.class);
method.setAccessible(true);
method.invoke(TARGET_OBJECT, arg1, arg2);

Invoke static method :

// Call private method
Method method = CLASS_NAME.class.getDeclaredMethod("METHOD_NAME", Argument1.class, Argument2.class);
method.invoke(null, arg1, arg2);

, ,


One thought on “[Java/Reflection] Access private fields/methods

  • Olivier says:

    Using Spring ReflectionUtils class :

    Field field = ReflectionUtils.findField(parentClass, attributeName);
    
    Method method = ReflectionUtils.findMethod(targetClass, methodName);
    

Leave a Reply

Your email address will not be published. Required fields are marked *