Access non-public Methods & Attributes
Sprache: English
Programmiersprache: Java
Veröffentlicht von: furykid [nicht registriert]
Letzte Änderung: 15.05.2006
Aufrufe: 877
Beschreibung
This class allows the access to ALL class methods and attributes using the reflection API. Although naturally not good OO practice, it is very handy for testing code which doesnt offer enough accessors to validate internal state.the class at.jps.reflection.MethodProxy implements this functionality.the class at.jps.reflection.CompleteSecretis a sample test targetthe class at.jps.reflection.Intruderis a demonstrates the basic functionalityusing the above testtarget.
Code
1
2 package at.jps.reflection;
3
4 /**
5 * this class represents a proxy for calling
6 * methods on ( or accessing attributes of ) an arbitrary object.
7 *
8 * it might be necessary to have
9 *
10 * permission java.lang.reflect.ReflectPermission "suppressAccessChecks";
11 *
12 * if running under a securitymanager, and accessing
13 * non-public methods.
14 *
15 * @author Johannes Plachy JPlachy@jps.at
16 * @version 1.0
17 */
18
19 import java.lang.reflect.*;
20 import java.security.*;
21
22 public class MethodProxy
23 {
24 /**
25 * this methods allows us to call a method of
26 * generic java class.
27 *
28 * @param classInstance Object
29 * a valid java class instance
30 * @param methodToCall String
31 * the name of a method to call
32 * @param parameterTypes Class[]
33 * the name of a method to call
34 * @param parameters an array of parameters to be passed to the method
35 * that will be invoken.
36 * @return an Object will be return that
37 * <OL>
38 * <LI>is null if the called method returns 'null'</LI>
39 * <LI>represents the methods return type</LI>
40 * <LI>contains an Exception if something went wrong</LI>
41 * </OL>
42 */
43
44 final public static Object callClassMethod( final Object classInstance, final String methodToCall, final Class[] parameterTypes, final Object[] parameters)
45 {
46 Object result = null;
47
48 try
49 {
50 // we are doing this with really great care....
51 // as undocumented in sun's own code
52 result = AccessController.doPrivileged( new PrivilegedExceptionAction()
53 {
54 public Object run() throws NoSuchMethodException, SecurityException, ClassNotFoundException
55 {
56 Class acClass = null;
57
58 Object primaryResult;
59
60 try
61 {
62 Method method = classInstance.getClass().getDeclaredMethod( methodToCall, parameterTypes );
63
64 method.setAccessible(true); // might need policy file changes - see class comment!
65
66 primaryResult = method.invoke( classInstance, parameters); // just do it !
67 }
68 catch ( Throwable x )
69 {
70 if ( x instanceof InvocationTargetException )
71 {
72 primaryResult = ((InvocationTargetException)x).getTargetException();
73 }
74 else
75 {
76 primaryResult = x;
77 }
78 }
79 return primaryResult;
80 }
81 } );
82
83 }
84 catch ( Exception e )
85 {
86 // e.getException() may be a NoSuchMethodException, SecurityException, or ClassNotFoundException or PrivilegedActionException
87 // however, we simply pass it on....
88
89 result = e;
90 }
91
92 return result;
93
94 }
95
96
97 /**
98 * this method allows us to access a class'
99 * attribute in a completely generic way
100 *
101 * @param classInstance
102 * a valid instance of the class
103 * that has the wanted attribute
104 * @param attributeToAccess
105 * the name of the Attribute in question
106 * @return an Object (wrapping if necessary) or containing
107 * the value of the attribute
108 * might contain an instance of Throwable
109 * if an error occurs
110 */
111 final public static Object accessClassField( final Object classInstance, final String attributeToAccess)
112 {
113 Object result = null;
114
115 try
116 {
117 // we are doing this with really great care....
118 // as undocumented in sun's own code
119 result = AccessController.doPrivileged( new PrivilegedExceptionAction()
120 {
121 public Object run() throws NoSuchMethodException, SecurityException, ClassNotFoundException
122 {
123 Class acClass = null;
124
125 Object primaryResult;
126
127 try
128 {
129 Field field = classInstance.getClass().getDeclaredField( attributeToAccess );
130
131 field.setAccessible(true); // might need policy file changes !
132
133 primaryResult = field.get(classInstance); // just do it !
134 }
135 catch ( Throwable x )
136 {
137 primaryResult = x;
138 }
139 return primaryResult;
140 }
141 } );
142
143 }
144 catch ( Exception e )
145 {
146 // e.getException() may be a NoSuchMethodException, SecurityException, or ClassNotFoundException or PrivilegedActionException
147 // however, we simply pass it on....
148
149 result = e;
150 }
151
152 return result;
153
154 }
155
156
157 /**
158 * this methods allows us to call a method of
159 * generic java class.
160 *
161 * @param classInstance
162 * a valid java class instance
163 * @param methodToCall
164 * the name of a method to call
165 * @param parameters an array of parameters to be passed to the method
166 * that will be invoken.
167 * ATTENTION - paramters itself and the contained
168 * arguments must not be NULL !!!
169 * @return an Object will be return that
170 * <OL>
171 * <LI>is null if the called method returns 'null'</LI>
172 * <LI>represents the methods return type</LI>
173 * <LI>contains an Exception if something went wrong</LI>
174 * </OL>
175 */
176 final public static Object callClassMethod( Object classInstance, String methodToCall, Object[] parameters)
177 {
178
179 Class[] parameterTypes = new Class[parameters.length];
180
181 for ( int i =0; i < parameters.length; i++ )
182 {
183 parameterTypes[i] = parameters[i].getClass();
184 }
185
186 return callClassMethod( classInstance, methodToCall, parameterTypes, parameters);
187
188 }
189
190 }
191
192 // -------------------
193 // test class
194
195
196 /**
197 * testclass for our reflection test
198 */
199 package at.jps.reflection;
200
201 /**
202 *
203 * @author Johannes Plachy JPlachy@jps.at
204 */
205 public class CompleteSecret
206 {
207 private String privateString = "String uno";
208 protected String protectedString = "String due";
209 String packageString = "string tres";
210
211 private byte privateByte = 123;
212 private int privateInt = 456;
213
214
215 public void method1()
216 {
217 System.out.println("This is method1");
218 }
219
220 public void method2()
221 {
222 System.out.println("This is method2");
223 }
224
225 protected void method3(StringBuffer sb, final Byte b)
226 {
227 System.out.println("This is method3");
228 System.out.println("Stringbuffer = "+sb.toString());
229 System.out.println("Byte = "+b.toString());
230 }
231
232 private void method4(String s, Integer i)
233 {
234 System.out.println("This is method4");
235 System.out.println("String = "+s);
236 System.out.println("Integer = "+i.toString());
237
238 }
239
240 void method5(String s, Integer i)
241 {
242 System.out.println("This is method5");
243 System.out.println("String = "+s);
244 System.out.println("Integer = "+i.toString());
245
246 }
247
248 }
249
250 //-------------------
251
252 // demo
253
254
255 package at.jps.reflection;
256
257
258 import java.lang.reflect.*;
259
260 public class Intruder
261 {
262
263 static void printResult( Object result)
264 {
265 if (result != null)
266 {
267 System.out.println("method returns : "+result);
268 }
269 else
270 {
271 System.out.println("method returns NULL - might be void !!");
272 }
273 }
274
275 static void callAllMethods()
276 {
277 Object object = new CompleteSecret();
278
279 System.out.println("\n try to access public method1 :");
280 printResult( MethodProxy.callClassMethod( object, "method1", new Object[]{} ));
281 System.out.println("\n try to access public method2 :");
282 printResult( MethodProxy.callClassMethod( object, "method2", new Object[]{} ));
283 System.out.println("\n try to access protected method3 :");
284 printResult( MethodProxy.callClassMethod( object, "method3", new Object[]{ new StringBuffer("Hi"), new Byte((byte)123)}));
285 System.out.println("\n try to access private method4 :");
286 printResult( MethodProxy.callClassMethod( object, "method4", new Object[]{ new String("Hello World"), new Integer(1234)}));
287 System.out.println("\n try to access package method5 :");
288 printResult( MethodProxy.callClassMethod( object, "method5", new Object[]{ new String("Hello World again"), new Integer(4321)}));
289 }
290
291 static void accessAllFields()
292 {
293 Object object = new CompleteSecret();
294
295 System.out.println("\n try to access private String :");
296 printResult( MethodProxy.accessClassField( object, "privateString"));
297 System.out.println("\n try to access protected String :");
298 printResult( MethodProxy.accessClassField( object, "protectedString"));
299 System.out.println("\n try to access package String :");
300 printResult( MethodProxy.accessClassField( object, "packageString"));
301 System.out.println("\n try to access private Byte :");
302 printResult( MethodProxy.accessClassField( object, "privateByte"));
303 System.out.println("\n try to access private int :");
304 printResult( MethodProxy.accessClassField( object, "privateInt"));
305 }
306
307
308 final public static void main( String[] args)
309 {
310 callAllMethods();
311 accessAllFields();
312 }
313
314 }
315
316
317
318
319
320
Noch kein Kommentar vorhanden
Dieses Snippet kommentieren
Name *
E-Mail (wird nicht angezeigt) *
Website
Kommentar *
Sicherheitscode *