Java Reflection, getMethod()

12,150

Solution 1

Make your test method public. I believe Class.getMethod() is limited to public methods.

Solution 2

Without you posting the exact exception and your output, its hard to tell, but I suspect it is because the classes are in two separate packages, and since the default modifiers for a method are just protected it fails.

Use getDeclaredMethod() to get a method that isn't normally visible.

Share:
12,150
Nibirue
Author by

Nibirue

Updated on June 28, 2022

Comments

  • Nibirue
    Nibirue almost 2 years

    I'm working with the basics of Java reflection and observing information on methods of classes. I need to get a method that matches specifications as described by the getMethod() function. However, when I do this I get a NoSuchMethodException, and I was hoping you could tell me why my implementation is incorrect.

    static void methodInfo2(String className) throws ClassNotFoundException, 
    
    NoSuchMethodException{
    
            Class cls = null;
            try{
                cls = Class.forName(className);
            } catch(ClassNotFoundException e){
                e.printStackTrace();
            }
            System.out.println("Cls:  "+cls);
    
    
            Method method1 = cls.getMethod("test", null);
            System.out.println("method1:  "+method1);
    
    
        }
    

    EDIT1:When I print out "Cls: "+cls, the output is "Cls: class a8.myclass2". Why does it append the class part? (the a8 is correct, so don't worry about that) /EDIT1

    This is the function I use to read in a class from my main function, and then I want to getMethod() with the parameters "test" and null, where "test" is the name of the method and null means the method has no parameters. The class I am reading in is called myclass2 which is here:

    package a8;
    
    public class myclass2 {
    
        void test(){
            //"takes no parameters"
            //"returns bool"
            //"name starts with test"
            //return true;
        }
    
    }
    

    As you can see, the method does infact exist in the class. If you could point out my mistake, I would really appreciate it.

  • Brandon Buck
    Brandon Buck over 12 years
    It does, and you beat me to it. +1 From the JavaDoc for getMethod(): "Returns a Method object that reflects the specified public member method of the class or interface represented by this Class object."
  • Nibirue
    Nibirue over 12 years
    Nope, they were within the same package. The answer above worked though.
  • jli
    jli over 12 years
    Might default to private then. Either way, if you use getDeclaredMethod() you can access anything.