How to access private fields, methods and constructors of a class in Java


On this page, we will talk about how can we access the private fields/members, methods, and constructors of another class in Java. We are familiar with the access modifiers of Java programming language. There are mainly three modifiers in Java.

  1. public- The public modifier specifies that the member can be accessed from everywhere.
  2. protected- The protected modifier specifies that the member can only be accessed within its own package and, in addition, by a subclass of its class in another package.
  3. private- The private modifier specifies that the member can only be accessed in its own class.

And if we don’t specify any modifiers, it will become no modifier that means visible to the package, the default. No modifiers are needed.

To access the private members of a class we can use java.lang.Class class and java.lang.reflect package. java.lang.reflect package have classes like to Field, Method, and Constructor for accessing the private fields, methods, and constructors respectively.

Access Private Fields

In order to access the private fields of any class, you need to know the name of field than by calling getDeclaredFields(String name) method of java.lang.Class class. Once you get the field reference you need to make it accessible by calling Field.setAccessible(true) because you are going to access private field.

Check the complete example for your better reference. In this example, the salary of employee declared as a private field.

Employee.java
package org.websparrow.access;

public class Employee {

	public String empName = "Diksha Rai";
	
	// private field
	private int empSalary = 34567;
}

Instantiate the Employee class in Hr class using Class.forName(String className) and declare the private field name in getDeclaredFields(String name) method.

Hr.java
package org.websparrow.access;

import java.lang.reflect.Field;

public class Hr {
	public static void main(String[] args) {
		try {

			Class<Employee> cls = (Class<Employee>) Class.forName("org.websparrow.access.Employee");

			Employee emp = new Employee();
			
			// declare the name of private field of Employee class
			Field field = cls.getDeclaredField("empSalary");
			
			// make it accessible 
			field.setAccessible(true);

			int salary = (int) field.get(emp);

			System.out.println("Employee name is " + emp.empName + " and his salary is " + salary + " rupees per month.");

		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
Output:

Run the above code, you will get the following output in your console log.

Employee name is Diksha Rai and his salary is 34567 rupees per month.

Access Private Methods

To access the private methods of the class, java.lang.Class class has a method getDeclaredMethod(String name). This method returns the java.lang.reflect.Method object.

NewEmployee class has a private method employeeDetails() which simply print the details of the employee on the console.

NewEmployee.java
package org.websparrow.access;

public class NewEmployee {

	public String id;
	public String name;
	public String organization;
	public String department;
	public String location;
	public int salary;

	public NewEmployee(String id, String name, String organization, String department, String location, int salary) {
		this.id = id;
		this.name = name;
		this.organization = organization;
		this.department = department;
		this.location = location;
		this.salary = salary;
	}

	// method declared as private
	private void employeeDetails() {
		System.out.println("Employee id is " + this.id + " and  name of employee is " + this.name
				+ ". He is working with " + this.organization + " under department " + this.department + " and earning "
				+ this.salary + " rupees per month.");
	}
}

HewHr class instantiate the class and accessed his private method.

NewHr.java
package org.websparrow.access;

import java.lang.reflect.Method;

public class NewHr {
	public static void main(String[] args) {
		try {

			Class<NewEmployee> cls = (Class<NewEmployee>) Class.forName("org.websparrow.access.NewEmployee");

			NewEmployee emp = new NewEmployee("EMP01", "Atul Rai", "Google Inc.", "Software Development", "Delhi", 180000);

			// declare the private method
			Method method = cls.getDeclaredMethod("employeeDetails");

			// set it accessible
			method.setAccessible(true);

			// invoke the method
			method.invoke(emp);

		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
Output:

Run the above code, you will get the following output in your console log.

Employee id is EMP01 and  name of employee is Atul Rai. He is working with Google Inc. under department Software Development and earning 180000 rupees per month.

Access Private Constructors

Similarly, we can access the private constructor of the class by using getDeclaredConstructors() method of java.lang.Class class.

Honda.java
package org.websparrow.access;

public class Honda {
	
	// private constructor 
	private Honda(){
		System.out.println("I am private constructor of Honda class.");
	}
}

Constructor class returns an array of objects reflecting all the constructors declared by the class represented by java.lang.Class object.

Car.java
package org.websparrow.access;

import java.lang.reflect.Constructor;

public class Car {
	public static void main(String[] args) {
		try {

			Class<?> cls = Class.forName("org.websparrow.access.Honda");

			Constructor<?>[] cons = cls.getDeclaredConstructors();
			cons[0].setAccessible(true);
			cons[0].newInstance();

		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
Output:

Run the above code, you will get the following output in your console log.

I am private constructor of Honda class.

Similar Posts

About the Author

Atul Rai
I love sharing my experiments and ideas with everyone by writing articles on the latest technological trends. Read all published posts by Atul Rai.