Call Private Method

Accessing a private method from outside the class can be achieved by altering the class's runtime behavior.

By utilizing the java.lang.Class class and the java.lang.reflect.Method class, it is possible to invoke a private method from an external class.

Required methods of Method class

The method setAccessible(boolean status) in Java's java.lang.reflect package allows you to modify the accessibility of a method by specifying a boolean status. If the method is inaccessible due to restrictions, a SecurityException is thrown.

2) The method public Object invoke(Object method, Object... args) is employed for invoking the specified method. It may throw exceptions like IllegalAccessException, IllegalArgumentException, and InvocationTargetException.

Required method of Class class

1) The getDeclaredMethod method in Java's programming language is a public method that takes in a String parameter name and an array of Class objects parameterTypes. It throws NoSuchMethodException and SecurityException. This method retrieves a Method object that represents the specified declared method from the class or interface identified by the Class object it is called on.

Example of calling private method from another class

Let's explore a straightforward example demonstrating how to invoke a private method from a different class.

File: A.java

Example

public class A {
  private void message(){System.out.println("hello java"); }
}

File: MethodCall.java

Example

import java.lang.reflect.Method;
public class MethodCall{
public static void main(String[] args)throws Exception{

	Class c = Class.forName("A");
	Object o= c.newInstance();
	Method m =c.getDeclaredMethod("message", null);
	m.setAccessible(true);
	m.invoke(o, null);
}
}

Output:

Output

hello java

Another example to call parameterized private method from another class

Consider the following example that demonstrates how to invoke a parameterized private method from a different class.

File: A.java

Example

class A{
private void cube(int n){System.out.println(n*n*n);}
}

File: M.java

Example

import java.lang.reflect.*;
class M{
public static void main(String args[])throws Exception{
Class c=A.class;
Object obj=c.newInstance();

Method m=c.getDeclaredMethod("cube",new Class[]{int.class});
m.setAccessible(true);
m.invoke(obj,4);
}}

Output:

Accessing Private Constructors of a class

In object-oriented programming, constructors are unique methods utilized for creating instances of a class. To retrieve a private constructor, the getDeclaredConstructor method is employed. This method allows access to both parameterless and parameterized constructors within a class. The code snippet below illustrates this concept.

FileName: PvtConstructorDemo.java

Example

// important import statements
import java.lang.reflect.Constructor;
import java.lang.reflect.Modifier;
import java.lang.reflect.InvocationTargetException;

class Vehicle 
{
 
// private fields of the class Vehicle
private Integer vId;
private String vName;

// parameterless constructor
private Vehicle()
{
    
}

// parameterized constructor
private Vehicle(Integer vId, String vName) 
{
   this.vId = vId;
   this.vName = vName;
}

// setter methods of the class Vehicle
public void setVehicleId(Integer vId)
{
   this.vId = vId;
}

public void setVehicleName(String vName)
{
   this.vName = vName; 
}


// getter methods of the class Vehicle
public Integer getVehicleId() 
{
   return vId;
}

public String getVehicleName() 
{
  return vName;
}
} 



public class PvtConstructorDemo 
{
// the createObj() method is used to create an object of 
// the Vehicle class using the parameterless constructor. 
public void craeteObj(int vId, String vName) throws InstantiationException, IllegalAccessException, 
IllegalArgumentException, InvocationTargetException, NoSuchMethodException 
{
// using the parametereless contructor
Constructor<Vehicle> constt = Vehicle.class.getDeclaredConstructor();

constt.setAccessible(true);
Object obj = constt.newInstance();
if (obj instanceof Vehicle) 
{
  Vehicle v = (Vehicle)obj;
   v.setVehicleId(vId);
   v.setVehicleName(vName);
     System.out.println("Vehicle Id: " +  v.getVehicleId());
     System.out.println("Vehicle Name: " +  v.getVehicleName());
}
}

// the craeteObjByConstructorName() method is used to create an object 
// of the Vehicle class using the parameterized constructor. 
public void craeteObjByConstructorName(int vId, String vName) throws NoSuchMethodException, SecurityException,
InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException
{

// using the parameterized contructor
Constructor<Vehicle> constt = Vehicle.class.getDeclaredConstructor(Integer.class, String.class);

if (Modifier.isPrivate(constt.getModifiers())) 
{
constt.setAccessible(true);
	
Object obj = constt.newInstance(vId, vName);
if(obj instanceof Vehicle)
{
     Vehicle v = (Vehicle)obj;
     System.out.println("Vehicle Id: " +  v.getVehicleId());
     System.out.println("Vehicle Name: " + v.getVehicleName());
}
}
}	
	
	

// delegating the responsibility to Java Virtual Machine (JVM) to handle the raised 
// exception
// main method
public static void main(String argvs[]) throws InstantiationException, 
IllegalAccessException, IllegalArgumentException, InvocationTargetException, 
NoSuchMethodException, SecurityException 
{
	
   // creating an object of the class PvtConstructorDemo
   PvtConstructorDemo ob = new PvtConstructorDemo();
   ob.craeteObj(20, "Indica");
   System.out.println(" -------------------------- ");
   ob.craeteObjByConstructorName(30, "Alto");
}
}

Output:

Output

Vehicle Id: 20
Vehicle Name: Indica
 -------------------------- 
Vehicle Id: 30
Vehicle Name: Alto

Input Required

This code uses input(). Please provide values below: