Access private fields and methods using reflection in java

In this post, we will see how to access private fields and methods using reflection in java.

Can you access private fields and methods using reflection?
Yes, you can. It is very easy as well. You just need to call .setAccessible(true) on field or method object which you want to access.

Access private field

Class.getDeclaredField(String fieldName) or Class.getDeclaredFields() can be used to get private fields.

💡 Did you know?

Class.getField(String fieldName) and Class.getFields() return public fields only, so you won’t be able to get private fields with them

Let’s see this with the help of example:
Consider a class named Employee which consists of two private fields name and age.

Create main class named PrivateFieldReflectionMain

When you run above class, you will get below output:
Output:

Name of Employee:John

As you can see, we are able to access private field name using reflection.

Access private method

If you want to invoke any method using reflection, you can go through invoke method using reflection.

Class.getDeclaredMethod(String methodName,Class<?>... parameterTypes) or Class.getDeclaredMethods() can be used to get private methods.

💡 Did you know?

Class.getMethod(String methodName,Class... parameterTypes) and Class.getMethods() return public methods only, so you won’t be able to get private methods with them

Let’s see this with the help of example:
We will access Employee‘s private method getAge() using reflection.

Create main class named

When you run above class, you will get below output:
Output:

Age of Employee: 33

As you can see, we are able to access private method getAge() using reflection.
That’s about how to access private fields and methods using reflection in java

Was this post helpful?

Leave a Reply

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