---
title: "利用java反射机制调用类的私有方法"
author: "RyanXL"
date: "2012-09-05T20:36:12Z"
tags: []
categories: ["编程语言"]
slug: "java"
draft: false
lastmod: "2012-09-05T20:37:39Z"
id: 1672249
url: "https://ryanxl.iteye.com/blog/1672249"
---

引用： [http://blog.chinaunix.net/uid-26884465-id-3337802.html](http://blog.chinaunix.net/uid-26884465-id-3337802.html)

 

测试后，确实可以调用类中的私有方法，前提是知道该私有方法的声明。测试代码如下:

 

class One {

One(){}

private void testMethod(){

System.out.println("invoked");

}

}

 

public class LittleTest {

@Test

public void test() throws Exception {

One one = new One();

Class cls= one.getClass();

Method method = cls.getDeclaredMethod("testMethod", null);

method.setAccessible(true);

method.invoke(one, null);

}

 

}