0% found this document useful (0 votes)
39 views2 pages

Reflection Example

This document defines a PrivateAccessor class that provides methods to access private fields and invoke private methods in classes. The getPrivateField method finds and returns the value of a private field by name, and invokePrivateMethod finds and invokes a private method by name, handling exceptions.
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
39 views2 pages

Reflection Example

This document defines a PrivateAccessor class that provides methods to access private fields and invoke private methods in classes. The getPrivateField method finds and returns the value of a private field by name, and invokePrivateMethod finds and invokes a private method by name, handling exceptions.
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

import java.lang.reflect.

Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import junit.framework.Assert;

/**
* Provides access to private members in classes.
*/
public class PrivateAccessor {

public static Object getPrivateField (Object o, String fieldName)


{
// Check we have valid arguments...
Assert.assertNotNull(o);
Assert.assertNotNull(fieldName);

// Go and find the private field...


final Field fields[] = o.getClass().getDeclaredFields();
for (int i = 0; i < fields.length; ++i) {
if (fieldName.equals(fields[i].getName())) {
try {
fields[i].setAccessible(true);
return fields[i].get(o);
}
catch (IllegalAccessException ex) {
Assert.fail ("IllegalAccessException accessing " +
fieldName);
}
}
}
Assert.fail ("Field '" + fieldName +"' not found");
return null;
}

public static Object invokePrivateMethod (Object o, String


methodName, Object[] params) {
// Check we have valid arguments...
Assert.assertNotNull(o);
Assert.assertNotNull(methodName);
Assert.assertNotNull(params);

// Go and find the private method...


final Method methods[] =
o.getClass().getDeclaredMethods();
for (int i = 0; i < methods.length; ++i) {
if (methodName.equals(methods[i].getName())) {
try {
methods[i].setAccessible(true);
return methods[i].invoke(o, params);
}
catch (IllegalAccessException ex) {
Assert.fail ("IllegalAccessException accessing " +
methodName);
}
catch (InvocationTargetException ite) {
Assert.fail ("InvocationTargetException
accessing " + methodName);
}
}
}
Assert.fail ("Method '" + methodName +"' not found");
return null;
}
}

You might also like