Access a private variable outside the class in Java

Hello Everyone. Now I am here to explain how to access a private variable outside the class in Java. We can overcome the problem of accessing private variables by using Java’s “reflection”.

Private variables are those variables which are defined privately for that particular class. These cannot be used outside the class. To use a variable outside the class:

1. Either make it public.

2. Or inherit the class in the present class and then use the variable.

In order to access a private variable through “reflection” concept, use two methods. One is getDeclaredMethod(String name), here name indicates the private variable-name which has to be accessed. The second one is setAccessible(boolean). If we set the boolean as true indicating, that we are accessing the variable. These two methods can be accessed by importing “java.lang.reflect.Field” package.

The methods required to access the private variables of the class are:

  • getDeclaredMethod(“variable-name”);
  • setAccessible(boolean);

Access a private variable outside the class in Java

import java.lang.Class;
import java.lang.reflect.Field;
class B{

    private int x=2;
public class Main
  public static void main(String[] args) throws Exception{
      Field f=B.class.getDeclaredField("x");
      B obj=new B();
      int o=(int)f.get(obj);


Reflection function helps to “reflect” on the structure of a program. In order to use private variable in different classes from your code, use reflection method. In order to access a private variable, set Field-object.setAccessible(true) . And this should be mentioned in the class where we are using a private variable. Then obtain the variable by using field object.

Hence, this is the way to use a private variable using reflection method instead using the inheritance concept and even avoiding making it a public variable.

I hope, this article can solve your problem.

Also, read:

Leave a Reply

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