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.
– Maicon Carraro
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.
– drgarcia1986
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?
– Filipe Miranda
Without Reflection it is not possible...
– user22408