Java反射,getMethod() [英] Java Reflection, getMethod()

查看:922
本文介绍了Java反射,getMethod()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Java反射的基础知识,并观察类的方法的信息。我需要得到一个匹配getMethod()函数所描述的规范的方法。但是,当我这样做,我得到一个NoSuchMethodException,我希望你能告诉我为什么我的实现是不正确的。

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:当我打印出Cls :+ cls,输出为Cls:class a8.myclass2。为什么它附加类部分? (a8是正确的,所以不要担心)/ 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

这是我用来从我的主要函数读入类的函数,然后我想要getMethod()与参数test和null,其中test是方法的名称,null表示该方法没有参数。我正在读的类叫做myclass2,它在这里:

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.

推荐答案

将您的测试方法设为公开。我相信Class.getMethod()只限于公共方法。

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

这篇关于Java反射,getMethod()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆