How to access the value of a private attribute in a class in Java without a public method?

1

How can I access the value of a private attribute in a class, from a class in another package, without using an access method, such as a getter?

class Person{
   private String name = "Someone";
}

Why would anyone do this?

One of the reasons is that you may need to serialize objects, such as Jackson does, transforming the values of the class fields into JSON . I can access using field getters, but if I do not have them, or they do not follow the JavaBeans pattern, in the example getName , how do I access the value of the field directly. Jackson itself allows you to configure whether you want to access through setters and getters, or with the fields directly. There is a real performance gain.

    
asked by anonymous 27.06.2015 / 15:04

1 answer

2

You can use reflection:

import java.lang.reflect.Field;

public class Expose {

    public static void main(String[] args) {
        Person person = new Person();
        Field secretField = null;
        try {
            secretField = Person.class.getDeclaredField("name");
        }
        catch (NoSuchFieldException e) {
            System.err.println(e);
            System.exit(1);
        }
        secretField.setAccessible(true); // break the lock!
        try {
            String wasHidden = (String) secretField.get(person);
            System.out.println("person.name = " + wasHidden);
        }
        catch (IllegalAccessException e) { 
            // this will not happen after setAcessible(true)
            System.err.println(e);
        }   
    }
}

Adapted example from link

    
27.06.2015 / 15:12