首页 > 解决方案 > 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
    }
}

标签: javanosuchelementexception

解决方案


getDeclaredMethod需要您传递参数类型,以便它可以解析重载方法。

由于您的foo方法有一个 type 参数String,因此以下应该有效:

Method m = Dummy.class.getDeclaredMethod("foo", String.class);

当然,您还需要更改invoke调用以传递字符串。


推荐阅读