Inspect and print nested Javabean properties

202 Views Asked by At

I have nested Javabeans, for example:

public BeanX {
   private int x1;
   private int x2;
   private List<BeanY> beany;
   …// getters and setters
}

public BeanY {
   private int x3;
   private int x4;
   private List<String> strings;
   …// getters and setters
}

In Java code, I only know the name of the first Javabean (BeanX). Is it possible to discover all properties of all types used by BeanX and print them for example as follows:

BeanX.x1
BeanX.x2
BeanX.beany (BeanY)
BeanY.x3
BeabY.x4
BeanY.strings  (String)

Reference: Javabean Introspector - what is in my List?

1

There are 1 best solutions below

3
On BEST ANSWER

You can do it using reflection API. This is just a basic code. You may want to check this tutorial for more info.

Main Class

import java.util.*;
import java.lang.reflect.*;
import java.io.*;


class Main
{
    public static void main (String[] args) throws java.lang.Exception
    {
        BeanX bx=new BeanX();
        printFields(bx.getClass());
    }

    static void printFields(Class bx ) throws java.lang.Exception{

            if(bx!=null && !bx.getSimpleName().equals("String")){
                for (Field field : bx.getDeclaredFields()){
                     field.setAccessible(true);
                     System.out.println(bx.getSimpleName()+"."+field.getName() 
                     +"->" +field.getGenericType());

                     if(field.getGenericType() instanceof ParameterizedType)
                        printFields((Class)(((ParameterizedType)field.getGenericType())
                        .getActualTypeArguments()[0]));
                }
            }
    }
}

class BeanX {
   private int x1;
   private int x2;
   private List<BeanY> beany;

   public void setBeany(List<BeanY> beany){
    this.beany=beany;
   }

}

class BeanY {
   private int x3;
   private int x4;
   private List<String> strings;

   public void setStrings(List<String> strings){
    this.strings=strings;
   }
}

output

BeanX.x1->  int
BeanX.x2->  int
BeanX.beany->  java.util.List<BeanY>
BeanY.x3->  int
BeanY.x4->  int
BeanY.strings-> java.util.List<java.lang.String>