gpt4 book ai didi

Java,返回方法作为引用

转载 作者:搜寻专家 更新时间:2023-11-01 01:26:11 24 4
gpt4 key购买 nike

我是 JAVA 开发新手。这是一个方法:

private Method getSomething()
{
for (Method m : getClass().getDeclaredMethods())
{
return m;
}
return notFound;
}

private void notFound()
{
throw new Exception();
}

不管它做了什么 - 如果它找到了一些东西,然后返回一个 Method - 如果没有,应该返回 notFound() 方法本身。所以热点在 return notFound; 行:如果我使用 return notFound(); 然后它返回它的值,而不是方法本身。我想要一个引用/指针之类的东西。所以 getSomething() 返回一些可以调用的东西,如果返回的方法使用错误,它应该触发该异常 - 所以它不是替换 return notFound; 的选项用 throw new Exception(); !或者第二个选项是创建一个 lambda 方法....

最佳答案

你需要打电话

this.getClass().getMethod("notFound")

获取当前/这个对象类的notFound方法。

所以就这样做:

return this.getClass().getMethod("notFound");

更多细节在这里:

Class.getMethod

编辑:

您也可以通过反射检索,即获取和调用私有(private)方法。

这是一个例子。

import java.lang.reflect.Method;


public class Test001 {

public static void main(String[] args) throws Exception {
Test002 obj = new Test002();
Method m = obj.getClass().getDeclaredMethod("testMethod", int.class);
m.setAccessible(true);

m.invoke(obj, 10);
m.invoke(obj, 20);

System.out.println(m.getName());
}


}

class Test002 {
private void testMethod(int x){
System.out.println("Hello there: " + x);
}
}

关于Java,返回方法作为引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24993271/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com