Midhilaj
Midhilaj

Reputation: 4987

Java get object variable name and get inner object variable name

We are using below code for getting variable name

public void printFieldNames(Object obj, Foo... foos) {
List<Foo> fooList = Arrays.asList(foos);
for(Field field : obj.getClass().getFields()) {
     if(fooList.contains(field.get()) {
          System.out.println(field.getName());
     }
  }
}

from

But some object contains another object for example

class A{
 String a="nil";
 B b;
}
class B{
int n1=0;
}

How to get object b varable details?
How to get custom list class name and object?
We need to get any object details assuming we don't know class name and inner object name

Upvotes: 0

Views: 291

Answers (1)

NiVeR
NiVeR

Reputation: 9786

I have completed the code by adding some constructors, but other than that it should be the same.

package com.example.demo;

import java.lang.reflect.Field;

public class TestMain {

    public class A {
        public String a = "nil";
        public B b;

        public A(String a, B b) {
            super();
            this.a = a;
            this.b = b;
        }
    }

    public class B {
        public int n1 = 0;

        public B(int n1) {
            super();
            this.n1 = n1;
        }
    }

    public static void main(String[] args) throws IllegalArgumentException, IllegalAccessException {
        TestMain test = new TestMain();
        B b = test.new B(10);
        A a = test.new A("Test", b);
        for (Field field : a.getClass().getDeclaredFields()) {
            field.setAccessible(true);
            String name = field.getName();
            Object value = field.get(a);
            if (value instanceof B) {
                B bV = (B) value;
                for (Field fieldB : bV.getClass().getDeclaredFields()) {
                    fieldB.setAccessible(true);
                    String name1 = fieldB.getName();
                    Object value1 = fieldB.get(b);
                    System.out.printf("Field name: %s, Field value: %s%n", name1, value1);
                }
            }
        }
    }
}

Upvotes: 1

Related Questions