java反射机制怎样调用类的私有方法

2025-03-22 12:17:16
推荐回答(3个)
回答(1):

为了一看就懂,请看下面的示例(假设调用 MyTest类的私有方法 privateMethod()):

public class ReflectionTest {
   
  public static void setObjectColor(Object obj) throws SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAcces***ception, InvocationTargetException{   // 核心代码加粗
    Class cls = obj.getClass();
    //获得类的私有方法
    Method method = cls.getDeclaredMethod("privateMethod", null);
    method.setAccessible(true); //没有设置就会报错
    //调用该方法
    method.invoke(obj, null);
  }
  public static void main(String args[]) throws SecurityException, IllegalArgumentException, NoSuchMethodException, IllegalAcces***ception, InvocationTargetException{
     
    setObjectColor(new MyTest());
  }
}
 //测试类
class MyTest{
   
  public void setMyTest(){
    System.out.println("setMyTest");
  }
  /**
   类的私有方法
   **/
  private void privateMethod(){
    System.out.println("调用了 private Method");
  }
   
}

回答(2):

的一段简易实例代码如下:

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
* @author thomaslwq
* @version 创建时间:Sep 4, 2012 9:53:49 PM
* 类说明
*/
public class ReflectionTest {

public static void setObjectColor(Object obj) throws SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAcces***ception, InvocationTargetException{
Class cls = obj.getClass();
//获得类的私有方法
Method method = cls.getDeclaredMethod("privateMethod", null);
method.setAccessible(true); //没有设置就会报错
//调用该方法
method.invoke(obj, null);
}
public static void main(String args[]) throws SecurityException, IllegalArgumentException, NoSuchMethodException, IllegalAcces***ception, InvocationTargetException{

setObjectColor(new MyTest());
}
}
//测试类
class MyTest{

public void setMyTest(){
System.out.println("setMyTest");
}
/**
类的私有方法
**/
private void privateMethod(){
System.out.println("调用了 private Method");
}

}

回答(3):

Class clazz = Bird.class;
Object object = clazz.newInstance();

Method method = clazz.getDeclaredMethod("fly");
method.setAccessible(true);
method.invoke(object);