Friday, November 16, 2007

PrivateFieldHelper Class

Heres a little class I wrote to set private fields. I plan to use it a little for testing, but only when I'm backed into a corner, and can't change code otherwise.



/**
*
* @author Josh Cough
*
*/
public class PrivateFieldHelperImpl implements PrivateFieldHelper {

Class clazz;

/**
*
* @param c
*/
public PrivateFieldHelperImpl(Class c) { this.clazz = c; }

/*
* (non-Javadoc)
* @see com.joshcough.reflect.PrivateFieldHelper#setStaticFieldValue(java.lang.String, java.lang.Object)
*/
public void setStaticFieldValue(String fieldName, Object newValue)
throws IllegalArgumentException, NoSuchFieldException {
setPrivateFieldValue(findPrivateStaticField(fieldName), null, newValue);
}

/*
* (non-Javadoc)
* @see com.joshcough.reflect.PrivateFieldHelper#getStaticFieldValue(java.lang.String)
*/
public Object getStaticFieldValue(String fieldName)
throws NoSuchFieldException, IllegalArgumentException {
return getPrivateFieldValue(null, findPrivateStaticField(fieldName));
}

/*
* (non-Javadoc)
* @see com.joshcough.reflect.PrivateFieldHelper#getInstanceFieldValue(java.lang.Object, java.lang.String)
*/
public Object getInstanceFieldValue(Object instance, String fieldName)
throws NoSuchFieldException, IllegalArgumentException {
return getPrivateFieldValue(instance, findPrivateInstanceField(fieldName));
}

/*
* (non-Javadoc)
* @see com.joshcough.reflect.PrivateFieldHelper#setInstanceFieldValue(java.lang.Object, java.lang.String, java.lang.Object)
*/
public void setInstanceFieldValue(Object instance, String fieldName, Object newValue)
throws IllegalArgumentException, NoSuchFieldException {
setPrivateFieldValue(findPrivateInstanceField(fieldName), instance, newValue);
}

/**
*
* @param f
* @return
* @throws
*/
private Object getPrivateFieldValue(Object instance, Field f) {
f.setAccessible(true);
Object o;
try {
o = f.get(instance);
} catch (IllegalAccessException e) {
throw new PrivateFieldException(e);
}
f.setAccessible(false);
return o;
}

/**
*
* @param f
* @param newValue
* @throws
*/
private void setPrivateFieldValue(Field f, Object instance, Object newValue){
f.setAccessible(true);
try {
f.set(instance, newValue);
} catch (IllegalAccessException e) {
throw new PrivateFieldException(e);
}
f.setAccessible(false);
}

/**
*
* @param fieldName
* @return
* @throws NoSuchFieldException
*/
private Field findPrivateStaticField(String fieldName) throws NoSuchFieldException {
for (Field f : clazz.getDeclaredFields()) {
if (f.getName().equals(fieldName)) {
if (Modifier.isStatic(f.getModifiers()))
return f;
}
}
throw new NoSuchFieldException();
}

/**
*
* @param fieldName
* @return
* @throws NoSuchFieldException
*/
private Field findPrivateInstanceField(String fieldName) throws NoSuchFieldException {
for (Field f : clazz.getDeclaredFields()) {
if (f.getName().equals(fieldName)) {
if (! Modifier.isStatic(f.getModifiers()))
return f;
}
}
throw new NoSuchFieldException();
}

}

1 comment: