I want to get the size of the object I built with java.reflection. Here is the code. I don't understand what I'm doing wrong. When I get the object I'm tried to use instrument interface but it doesn't work. Thanks for helping !
public String analayzeData(Object obj) throws IllegalArgumentException, IllegalAccessException{
Class c = obj.getClass();
System.out.println(sizer.getObjectSize(obj));
String dataText="*************Start of " + c.getSimpleName() + " Class*************\n";
Class superclass = c.getSuperclass();
if(superclass!=null && !superclass.isAssignableFrom(Object.class)){
Field[] superField = superclass.getDeclaredFields();
for(Field field : superField){
field.setAccessible(true);
Object fieldVal = field.get(obj);
dataText+=field.getName() + " = " + fieldVal + "\n";
}
}
// Instrumentation objectSizes =null;
Field[] fieldType= c.getDeclaredFields();
for(Field field : fieldType){
field.setAccessible(true);
dataText+=field.getName() + ":";
Object fieldVal = field.get(obj);
if(fieldVal instanceof ArrayList){
ArrayList<?> arrayListField = (ArrayList<?>)fieldVal;
dataText+="Size of " + field.getName() +" ArrayList = " + arrayListField.size() + "\n";
for (int i=0; i < arrayListField.size();i++){
dataText+=analayzeData(arrayListField.get(i));
}
dataText+="****End of " + field.getName() + "List****\n";
}
else
dataText+= " = " + fieldVal+"\n";
}
dataText+="*************End of " + c.getSimpleName() + " Class*************\n";
return dataText ;
}
}
class sizer{
private static Instrumentation instrumentation;
public static void premain(String args, Instrumentation inst) {
instrumentation = inst;
}
public static long getObjectSize(Object o) {
return instrumentation.getObjectSize(o);
}
}
Aucun commentaire:
Enregistrer un commentaire