| Author |
Trouble with Java Reflection
|
M Burke
Ranch Hand
Joined: Jun 25, 2004
Posts: 375
|
|
I wrote a class\method where I can pass any class into it and get the instance parameter name-value pairs. But it has some limitations: The ReflectMgr class must be in the same package as the class being inspected or it can't see protected and private members. Also, it does not get inherited variables. Does anyone know of a way I can overcome these limitations?
My Class...
import java.lang.reflect.Field;
import java.util.Collection;
public class ReflectMgr {
final static private String NL = System.getProperty("line.separator");
final static private String NULL = "Null";
final static private String UNV = "Unavailable in Package Context";
final static private String MSG_SP_INPUT_SEARCH_PARAM_OBJ_NAME = "Object Name: ";
final static private String MSG_SP_INPUT_PARAM_NAME = "Instance Name: ";
final static private String MSG_SP_INPUT_PARAM_VALUE ="Value: ";
/**
* Used for inspecting object output
* @param obj
* @return
*/
public static String objToString(Object obj){
String debugMsg = "";
String value = "";
Class<?> oClass = obj.getClass();
debugMsg = NL + MSG_SP_INPUT_SEARCH_PARAM_OBJ_NAME + oClass.getName() + NL;
Field[] fs = oClass.getDeclaredFields();
for(Field f: fs){
try {
value = f.get(obj).toString();
} catch (IllegalArgumentException e1) {
value = NULL;
} catch (IllegalAccessException e1) {
value = UNV;
}catch (Exception e1) {
value = NULL;
}
try {
debugMsg = debugMsg + MSG_SP_INPUT_PARAM_NAME + f.getName() + " " +
MSG_SP_INPUT_PARAM_VALUE + value + NL;
} catch (Exception e) {}//eat errors so it does not obscure true causes
}
return debugMsg;
}
}
|
 |
Ernest Friedman-Hill
author and iconoclast
Marshal
Joined: Jul 08, 2003
Posts: 24081
|
|
You can get inherited members by asking the class for its parent, and then doing the same thing for the parent class (and grandparent, etc.)
You can access protected/private methods using the setAccessible() method of java.lang.reflect.AccessibleObject .
|
[Jess in Action][AskingGoodQuestions]
|
 |
M Burke
Ranch Hand
Joined: Jun 25, 2004
Posts: 375
|
|
Ernest Friedman-Hill wrote:You can get inherited members by asking the class for its parent, and then doing the same thing for the parent class (and grandparent, etc.)
You can access protected/private methods using the setAccessible() method of java.lang.reflect.AccessibleObject .
Thank you, Ernest. That will to the trick.
|
 |
 |
|
|
subject: Trouble with Java Reflection
|
|
|