-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPrivateAccessor.java
More file actions
89 lines (80 loc) · 3.33 KB
/
PrivateAccessor.java
File metadata and controls
89 lines (80 loc) · 3.33 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
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 instanceOfClass, String fieldName) {
// Check we have valid arguments...
Assert.assertNotNull(instanceOfClass);
Assert.assertNotNull(fieldName);
// Find private field.
final Field fields[] = instanceOfClass.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(instanceOfClass);
} catch (IllegalAccessException ex) {
Assert.fail("IllegalAccessException accessing "
+ new Object[0]);
}
}
}
Assert.fail("Field '" + fieldName + "' not found");
return null;
}
public static void setPrivateField(Object instanceOfClass, String fieldName, Object value) {
// Check we have valid arguments...
Assert.assertNotNull(instanceOfClass);
Assert.assertNotNull(fieldName);
Assert.assertNotNull(value);
// Find private field.
final Field fields[] = instanceOfClass.getClass().getDeclaredFields();
for (int i = 0; i < fields.length; ++i) {
if (fieldName.equals(fields[i].getName())) {
try {
// Set private field with value provided.
fields[i].setAccessible(true);
fields[i].set(instanceOfClass, value);
return;
} catch (IllegalAccessException ex) {
Assert.fail("IllegalAccessException accessing "
+ new Object[0]);
}
}
}
Assert.fail("Field '" + fieldName + "' not found");
}
public static Object invokePrivateMethod(Object instanceOfClass, String methodName,
Object[] params) {
// Check for invalid arguments.
Assert.assertNotNull(instanceOfClass);
Assert.assertNotNull(methodName);
// Find private method.
final Method methods[] = instanceOfClass.getClass().getDeclaredMethods();
for (int i = 0; i < methods.length; ++i) {
if (methodName.equals(methods[i].getName())) {
try {
methods[i].setAccessible(true);
// invoke private method with provided params.
if (params == null) {
return methods[i].invoke(instanceOfClass);
} else {
return methods[i].invoke(instanceOfClass, 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;
}
}