[Java] Accessing private fields

The problem: you have to use class that we can’t modify for some reason. You want to get or set values of fields (name, surname) of class User, but cannot do it in the other way that calling toString() method and parsing return value (using methods of this class).
Let’s see the code:

class User {
        private String name;
        private String surname;
        public User(String name, String surname) {
                this.name = name;
                this.surname = surname;
        }
        public String toString() {
                return name + " " + surname;
        }
}

Luckily, java comes with the solution – java.lang.reflect api:

import java.lang.reflect.Field;
public class ReflectionTest {
        public static void main(String[] args) throws Exception{
                User user = new User("Paul", "Tyson");
                System.out.println("Name of our user before: " + user.toString());
                // now you cannot change user's name and surname, unless
                // you use reflection
                // get declared field object:
                Field field = User.class.getDeclaredField("name");
                // cannot do User.class.getField("name");
                // because this field is not accesible
                System.out.println("is field accesible? " + field.isAccessible());
                // all magic: set accessible true!
                field.setAccessible(true);
                System.out.println("is field accesible? " + field.isAccessible());
                // setting value
                field.set(user, "Mike");
                // returning to previous field accesible state is unnecessary in this case
                // but if you want to use this field object in future - return
                // to first state
                System.out.println("Name of our user after: " + user.toString());
        }
}

which prints:

Name of our user before: Paul Tyson
is field accesible? false
is field accesible? true
Name of our user after: Mike Tyson

To sum up, with help of the reflection api we can do a lot of things, but generally it is not recommended to write such code. It is hard to maintain and may be hard to understand. There are some situations, when you have to do it, but if you have another way of fixing your problem – don’t use reflection.

This entry was posted in coding, java, standard edition and tagged , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*


*

You may use these HTML tags and attributes: