Saturday, 15 May 2010

Generic "quasi toString()" using Java Class reflection -



Generic "quasi toString()" using Java Class reflection -

i have been trying create robust code prints out java class debugging. that, utilize reflections. in order protect against recursive definition such "boolean contains static final boolean true", ignore fields equal parents. utilize string += out of laziness. doesn't have efficient.

yet, there nicer way recursive description of objects reflections?

public string reflectionshowfields(object parentobject) { string stringdata = ""; (field field:parentobject.getclass().getfields()) { seek { class<?> type = field.gettype(); string typesimplename = type.getsimplename(); object fieldvalue = field.get(parentobject); string fieldname = field.getname(); if (type.isprimitive() || type.isenum() || charsequence.class.isassignablefrom(type)) { stringdata += string.format("%s: %s\n", fieldname, fieldvalue); } else if (iterable.class.isassignablefrom(type)) { stringdata += string.format(">>> %s[%s]: \n", fieldname, typesimplename); (object item:(iterable)fieldvalue) { stringdata += reflectionshowfields(item); } stringdata += string.format("<<< %s[%s]: \n", fieldname, typesimplename); } else if (!fieldvalue.equals(parentobject)) { stringdata += string.format(">>> %s[%s]: %s \n--------\n", fieldname, typesimplename, fieldvalue.tostring()); stringdata+= reflectionshowfields(fieldvalue); stringdata += string.format("<<< %s[%s]: \n", fieldname, typesimplename); } } grab (illegalaccessexception ignored) {} } homecoming stringdata; }

you utilize apache commons-lang reflectiontostringbuilder https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/builder/reflectiontostringbuilder.html

java reflection

No comments:

Post a Comment