Durga Dutt
Durga Dutt

Reputation: 4113

Get private field values using Reflection API java

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.UnknownHostException;
import java.util.ArrayList;

import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.MongoClient;

public class MongoTest {

    /**
     * @param args
     * @throws UnknownHostException 
     * @throws ClassNotFoundException 
     * @throws IllegalAccessException 
     * @throws IllegalArgumentException 
     */
    public static void main(String[] args) throws UnknownHostException, ClassNotFoundException, IllegalArgumentException, IllegalAccessException {
        Employee employee= new Employee();
        employee.setFirstname("Durga Dutt");
        employee.setLastname("Pandey");
        employee.setAge(28);
        employee.setSalary(100035);

        Class<?> cl= Class.forName("Employee");
        Field[] fields= cl.getDeclaredFields();

        for(int i=0;i<fields.length;i++)
        {
            System.out.println(fields[i].get(employee));
        }

    }

}

Above program is returning values for public fields but not working on private member. I have declared getters and setters in my POJO class.

Any ideas ?

Upvotes: 0

Views: 1733

Answers (1)

Marco Acierno
Marco Acierno

Reputation: 14847

To get a value of a private field you should set it as accessible by using setAccessible.

getDeclaredFields will allow you to see names of private fields, not the value.

Upvotes: 4

Related Questions