java - How do I use reflection to access a private method?
问题描述
I'm trying to access private method within reverse() in Java.
I've tried my best to make it possible, but failed at last. Can anyone help me to solve this? I just need a success run. Maybe I can change the code. Maybe I'm doing this the wrong way?
Error:
Exception in thread "main" java.lang.NoSuchMethodException: Dummy.foo()
at java.lang.Class.getDeclaredMethod(Class.java:2130)
at Test.main(Dummy.java:22)
Process completed.
My code:
import java.util.*;
import java.lang.reflect.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
class Dummy{
private void foo(String name) throws Exception{
BufferedReader n = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Please give name: ");
name = n.readLine();
StringBuffer o = new StringBuffer(name);
o.reverse();
System.out.print("Reversed string: "+o);
}
}
class Test{
public static void main(String[] args) throws Exception {
Dummy d = new Dummy();
Method m = Dummy.class.getDeclaredMethod("foo");
//m.invoke(d);// throws java.lang.IllegalAccessException
m.setAccessible(true);// Abracadabra
m.invoke(d);// now its OK
}
}
解决方案
getDeclaredMethod
需要您传递参数类型,以便它可以解析重载方法。
由于您的foo
方法有一个 type 参数String
,因此以下应该有效:
Method m = Dummy.class.getDeclaredMethod("foo", String.class);
当然,您还需要更改invoke
调用以传递字符串。
推荐阅读
- javascript - How to 'npm run build' on the server regularly
- ios - 我如何能够在下面的代码中实现洗牌功能?
- flutter - 如何在 Flutter dart 的 ListView 中添加浮动操作按钮
- c++ - 将函数返回分配给堆的正确方法
- python - 在为 Maya 编写 Python 脚本时使用类
- java - 如何将 Kotlin 中的伴随对象输出作为 Java 对象创建中的参数传递?
- php - 将 3 个 SQL 查询变成 1 个
- python - 谷歌地球引擎:错误:无法使用“in”运算符在表 3 中搜索“类型”
- c# - ASP.NET Core ASW S3 - 我们计算的请求签名与您提供的签名不匹配
- c++ - 用 Qt 解析 GLTF 缓冲区