• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Trouble with Java Reflection

 
M Burke
Ranch Hand
Posts: 399
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 24204
34
Chrome Eclipse IDE Mac OS X
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 .
 
M Burke
Ranch Hand
Posts: 399
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic