How to register internal elements of an arbitrary object in Java?

I have a Java object with some unknown structure. Now I want to output this structure (properties and their values) to a log file. And, of course, I'm interested in doing this in recursive mode. Are there any libraries that can help me?

+6
source share
8 answers

XStream is extremely good at printing object graphs, even processing cycles, without any additional setup or extra code in your classes (i.e. mess with toString ()). Just add a library, and you can do it on anything and get a nice, useful conclusion:

log.debug("The object: {}", new XStream().toXML(anyObject)); 

This will give you XML output. If you prefer JSON, you can get it with a little extra work, described in detail in the XStream JSON tutorial .

+6
source

I suggest you look at either Apache Commons BeanUtils or Apache Commons Lang, in particular ReflectionToStringBuilder.

+4
source

Java serialization that ships with Java should do the trick. It will be in binary format.

There is also XML serialization that can be provided by JAXB

0
source

you can use reflection

getClass, and then go to each instance variable and continue (some objects may be processed specifically (e.g. strings))

0
source

You must use reflection. Take a look at the java.lang.Class class, in particular the .getFields() method.

0
source

I found Apache Commons ToStringBuilder.reflectionToString() very useful. To get recursion, you can override each Object toString () method with a call to this function passing through this .

http://commons.apache.org/lang/api-2.6/org/apache/commons/lang/builder/ToStringBuilder.html

0
source

The java reflection API will give you access to all of these materials (private members and all). To get private members, you need to get yourObject.getClass().getDeclaredFields() to access the private field, remember to call it yourField.setAccesible(true) .

Of course, you will encounter problems very quickly by doing your own class, doing this through reflection. The main problems arise when trying to finally print the value and determine if it is an enumeration, a primitive, primitive array, etc. You can use the Class.isPrimitive method to help understand what this step is. To access the elements of an array, use the java.lang.reflect.Array class.

The best option that was published earlier is to use ReflectionToStringBuilder in apache.

0
source

The json serial editor will do this job, for example. using gson:

 import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.gson.Gson; ... private static final Logger LOG = LoggerFactory.getLogger(Your.class); ... Object obj = ...; LOG.info(new Gson().toJson(obj)); 
0
source

Source: https://habr.com/ru/post/892855/


All Articles