如何在Java中从另一个类调用私有方法

您可以通过更改类的运行时行为来从类外部调用私有方法。

通过使用java.lang.Class类和java.lang.reflect.Method类,我们可以从任何其他类中调用私有方法。

Method类的必需方法

1)public void setAccessible(boolean status)throws SecurityException:设置方法的可访问性。

2)public Object invoke(Object method,Object ... args)throws IllegalAccessException,IllegalArgumentException,InvocationTargetException:用于调用方法。

Class类的必需方法

1)public Method getDeclaredMethod(String name,Class [] parameterTypes)throws NoSuchMethodException,SecurityException:返回反映此Class对象所表示的类或接口的指定声明方法的Method对象。

从另一个类调用私有方法的示例

让我们看一个简单的示例,从另一个类调用私有方法。

文件:A.java

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

文件:MethodCall.java

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);  
}  
}  

输出:

hello java

从另一个类调用带参数的私有方法的另一个示例

让我们看一个示例,从另一个类调用带参数的私有方法。

文件:A.java

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

文件:M.java

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);  
}}  

输出:

64

访问类的私有构造函数

我们知道类的构造函数是一种特殊类型的方法,用于实例化类。要访问私有构造函数,我们使用getDeclaredConstructor()方法。getDeclaredConstructor()方法用于访问类的无参数和带参数构造函数。以下示例显示了相同的内容。

文件名:PvtConstructorDemo.java

// 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");  
}  
}  

输出:

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

标签: java, Java面试题, Java下载, java教程, java技术, Java学习, Java学习教程, Java语言, Java开发, Java入门教程, Java进阶教程, Java高级教程, Java笔试题, Java编程思想