java中如何知道一个类是否有方法以及如何调用它

发布于 2024-12-22 21:30:14 字数 124 浏览 2 评论 0原文

我需要知道java类是否有该方法

public double getValue() 

(如果有)。我需要调用该方法。

抱歉,我忘了说这需要在运行时完成

I need to know if a java class has the method

public double getValue() 

if there is a method. I need call the method.

Sorry, I forgot to say that this need to do at runtime

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

段念尘 2024-12-29 21:30:14

您可以使用 Class.getMethod() 获取 Method 对象,然后 Method.call() 调用该方法。

getMethod() 将抛出 < code>NoSuchMethodException 如果该类没有具有所请求名称和签名的方法。

You could use Class.getMethod() to get the Method object, and then Method.call() to invoke the method.

getMethod() will throw NoSuchMethodException if the class doesn't have a method with the requested name and signature.

墟烟 2024-12-29 21:30:14

您需要获取类,然后获取类中的方法。假设焦虑是你的目标。

Object angst = new Object();
Method[] methods= angst.getClass().getMethods();
for(i=0; i<methods.length; i++) {
    if(methods[i].getName().equals("getValue") {
        //some boolean stuff
    }
}

You need to get the class, and then the methods from the class. Assume angst is your object.

Object angst = new Object();
Method[] methods= angst.getClass().getMethods();
for(i=0; i<methods.length; i++) {
    if(methods[i].getName().equals("getValue") {
        //some boolean stuff
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文