java代码中如何调用一个类的私有方法呢?
下文笔者讲述Java“调用类的私有方法”的方法分享,如下所示:
实现思路: 借助反射,即可调用一个类的私有方法例:
package com.java265.other; import java.lang.reflect.Method; public class test { /* * java265.com “使用反射调用私有方法”的方法分享 */ public static void main(String[] args) throws Exception { test t = new test(); Method method = t.getClass().getDeclaredMethod("testFun"); method.setAccessible(true); Object r = method.invoke(t); } private void testFun() { System.out.println("这是一个私有方法!"); } }
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。