Search code examples
javanosuchelementexception

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
    }
}

Solution

  • getDeclaredMethod needs you to pass the parameter types so that it can resolve overloaded methods.

    Since your foo method has a single parameter of type String, the following should work:

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

    And of course you also need to change the invoke call to pass a string.