Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

About this user

« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS 

Accessing private methods and fields of a Java class

This class uses reflection to enable you to invoke private methods on a class, or access its private fields. This can be useful for unit testing.

   1  
   2  import java.lang.reflect.Field;
   3  import java.lang.reflect.InvocationTargetException;
   4  import java.lang.reflect.Method;
   5  
   6  import junit.framework.Assert;
   7  
   8  /**
   9   * Provides access to private members in classes.
  10   */
  11  public class PrivateAccessor {
  12  	
  13    public static Object getPrivateField (Object o, String fieldName) {   
  14  	 // Check we have valid arguments... 
  15      Assert.assertNotNull(o);
  16      Assert.assertNotNull(fieldName);
  17      
  18      // Go and find the private field... 
  19      final Field fields[] = o.getClass().getDeclaredFields();
  20      for (int i = 0; i < fields.length; ++i) {
  21        if (fieldName.equals(fields[i].getName())) {
  22          try {
  23            fields[i].setAccessible(true);
  24            return fields[i].get(o);
  25          } 
  26          catch (IllegalAccessException ex) {
  27            Assert.fail ("IllegalAccessException accessing " + fieldName);
  28          }
  29        }
  30      }
  31      Assert.fail ("Field '" + fieldName +"' not found");
  32      return null;
  33    }
  34    
  35    public static Object invokePrivateMethod (Object o, String methodName, Object[] params) {   
  36  		 // Check we have valid arguments... 
  37  	    Assert.assertNotNull(o);
  38  	    Assert.assertNotNull(methodName);
  39  	    Assert.assertNotNull(params);
  40  	    
  41  	    // Go and find the private method... 
  42  	    final Method methods[] = o.getClass().getDeclaredMethods();
  43  	    for (int i = 0; i < methods.length; ++i) {
  44  	      if (methodName.equals(methods[i].getName())) {
  45  	        try {
  46  	          methods[i].setAccessible(true);
  47  	          return methods[i].invoke(o, params);
  48  	        } 
  49  	        catch (IllegalAccessException ex) {
  50  	          Assert.fail ("IllegalAccessException accessing " + methodName);
  51  	        }
  52  	        catch (InvocationTargetException ite) {
  53  	        	Assert.fail ("InvocationTargetException accessing " + methodName);	        	
  54  	        }
  55  	      }
  56  	    }
  57  	    Assert.fail ("Method '" + methodName +"' not found");
  58  	    return null;
  59  	  }  
  60  }
« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS