Sunday, 2 August 2015

How to print values of an object in Java when you do not have the source code for the class?

                 You can get all fields by Class#getDeclaredFields(). Each returns a Field object of which you in turn can use the get() method to obtain the value. To get the values for non-public fields, you only need to set Field#setAccessible() to true.

Example :-
-------------------------------------------------------------------------------------------------------------------
package com.test;

public class TestBean {
   
    String name;
    String job;
    String company;
    String sal;
   
    //Initialising the properties.
    TestBean() {
        this.name = "java";
        this.job = "developer";
        this.company = "XYZ";
        this.sal = "10000";
    }
   
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getJob() {
        return job;
    }
    public void setJob(String job) {
        this.job = job;
    }
    public String getCompany() {
        return company;
    }
    public void setCompany(String company) {
        this.company = company;
    }
    public String getSal() {
        return sal;
    }
    public void setSal(String sal) {
        this.sal = sal;
    }
}

------------------------------------------------------------------------------------------------------------------ 
package com.test;

import java.lang.reflect.Field;

public class PrintPropertiesFromObject {

    public static void main(String[] args) throws RuntimeException, IllegalAccessException {
       
        TestBean testBeanObject = new TestBean();
       
        for (Field field : testBeanObject.getClass().getDeclaredFields()) {
            field.setAccessible(true);
            String name = field.getName();
            Object value = field.get(testBeanObject);
            System.out.printf("Field name: %s, Field value: %s%n", name, value);
        }
    }
}

 -----------------------------------------------------------------------------------------------------------------
Output :-
Field name: name, Field value: java
Field name: job, Field value: developer
Field name: company, Field value: XYZ
Field name: sal, Field value: 10000

No comments:

Post a Comment