Skip to main content
deleted 2 characters in body
Source Link

If you cannot use external APIs or dont want to, you can still use pure standard JDK API to access private methods using reflection. Here is an example

MyObject obj = new MyObject();
Method privateMethod = MyObject.class.getDeclaredMethod("getFoo", null);
privateMethod.setAccessible(true);
String returnValue = (String) privateMethod.invoke(obj, null);
System.out.println("returnValue = " + returnValue);

Check Java Tutorial http://docs.oracle.com/javase/tutorial/reflect/ or Java API http://docs.oracle.com/javase/7/docs/api/java/lang/reflect/package-summary.html for more information.

As @kij mentioncited on his answer there are times when a simple solution using reflection is really good to test a private method.

If you cannot use external APIs or dont want to, you can still use pure standard JDK API to access private methods using reflection. Here is an example

MyObject obj = new MyObject();
Method privateMethod = MyObject.class.getDeclaredMethod("getFoo", null);
privateMethod.setAccessible(true);
String returnValue = (String) privateMethod.invoke(obj, null);
System.out.println("returnValue = " + returnValue);

Check Java Tutorial http://docs.oracle.com/javase/tutorial/reflect/ or Java API http://docs.oracle.com/javase/7/docs/api/java/lang/reflect/package-summary.html for more information.

As @kij mention on his answer there are times when a simple solution using reflection is really good to test a private method.

If you cannot use external APIs or dont want to, you can still use pure standard JDK API to access private methods using reflection. Here is an example

MyObject obj = new MyObject();
Method privateMethod = MyObject.class.getDeclaredMethod("getFoo", null);
privateMethod.setAccessible(true);
String returnValue = (String) privateMethod.invoke(obj, null);
System.out.println("returnValue = " + returnValue);

Check Java Tutorial http://docs.oracle.com/javase/tutorial/reflect/ or Java API http://docs.oracle.com/javase/7/docs/api/java/lang/reflect/package-summary.html for more information.

As @kij cited on his answer there are times when a simple solution using reflection is really good to test a private method.

Source Link

If you cannot use external APIs or dont want to, you can still use pure standard JDK API to access private methods using reflection. Here is an example

MyObject obj = new MyObject();
Method privateMethod = MyObject.class.getDeclaredMethod("getFoo", null);
privateMethod.setAccessible(true);
String returnValue = (String) privateMethod.invoke(obj, null);
System.out.println("returnValue = " + returnValue);

Check Java Tutorial http://docs.oracle.com/javase/tutorial/reflect/ or Java API http://docs.oracle.com/javase/7/docs/api/java/lang/reflect/package-summary.html for more information.

As @kij mention on his answer there are times when a simple solution using reflection is really good to test a private method.