在不同编程语言里,“反射调用私有方法”写法不一样。下面以Java和**C#**为例说明(最常用),并顺带提一下 Python。
Class 对象MethodsetAccessible(true)invokeclass Demo {
private String hello(String name) {
return "Hello, " + name;
}
}
public class Test {
public static void main(String[] args) throws Exception {
Demo obj = new Demo();
// 1. 获取 Class
Class<?> clazz = obj.getClass();
// 2. 获取私有方法
Method method = clazz.getDeclaredMethod("hello", String.class);
// 3. 解除私有访问限制
method.setAccessible(true);
// 4. 调用
String result = (String) method.invoke(obj, "Tom");
System.out.println(result);
}
}
⚠️ 注意:
getDeclaredMethod 才能拿到私有方法setAccessible(true) 可能受 模块系统(Java 9+) 或 SecurityManager 限制using System;
using System.Reflection;
class Demo
{
private string Hello(string name)
{
return "Hello, " + name;
}
}
class Program
{
static void Main()
{
var obj = new Demo();
var method = typeof(Demo).GetMethod(
"Hello",
BindingFlags.NonPublic | BindingFlags.Instance
);
var result = (string)method.Invoke(obj, new object[] { "Tom" });
Console.WriteLine(result);
}
}
class Demo:
def __hello(self, name):
return f"Hello, {name}"
d = Demo()
result = d._Demo__hello("Tom")
print(result)
或通过 getattr:
method = getattr(d, "_Demo" + "__hello")
method("Tom")
如果你说的是 某一种具体语言(如 Kotlin / Go / C++),可以告诉我,我给你对应写法。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。