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

Asked

Viewed 765 times

1

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

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

Why would anyone do that?

One of the reasons is that you may need to serialize objects such as the Jackson makes, transforming the values of class fields into JSON. I can access using field getters, but in case I don’t have them, or they don’t follow the Javabeans pattern, in the example getName, how I access the value of the field directly. Jackson itself allows you to set up if you want to access through setters and getters, or with the fields directly. There is a real performance gain.

  • I believe that not pq would stick to the whole idea of encapsulation, even if involving inheritance and other stops.

  • 2

    Without Reflection you will only be able to access the attribute if it is in the same class package, otherwise no, even pq this doesn’t make much sense.

  • The name field is private. If the class you want to access is in the same package, it cannot access the name field, because this is private, it would have to be private package. The point is, in which scenario, Reflection does not work?

  • Without Reflection it is not possible...

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 of https://github.com/fluentpython/example-code/blob/master/09-pythonic-obj/private/Expose.java

  • Notice that I ask if it is always possible to do this. And it is not always possible to do so. I wanted to know why in certain cases this code you posted may not work. I will detail more the question.

  • Well, as you put it (after I even responded) that Reflection doesn’t help you, it might disregard my answer.

  • Hello @drgarcia1986, I simplified my question, it was confused, now I think it’s clearer, and yes your answer perfectly meets the current question. Thank you very much.

  • Cool @Filipegonzagamiranda glad you helped

Browser other questions tagged

You are not signed in. Login or sign up in order to post.