我正在使用反射行记录函数名。
this.getClass().getEnclosingMethod().getName()但是它将抛出NULLPointerException,因为this.getClass().getEnclosingMethod()将返回Null,
而
this.getClass().getMethods()[0].getName() working fine.为什么反射方法getEnclosingMethod()抛出空指针异常。它的修复方法是什么?
Java版本: 11
发布于 2022-01-19 08:22:04
让我们首先了解一下getEnclosingMethod()是用于什么的。
示例: Main.java
public class Main {
public Object getName(){
class Example{
}
return new Example();
}
public static void main(String[] args) {
Main main = new Main();
Class subClass = main.getName().getClass();
System.out.println("EnclosingMethod of Main: "
+ subClass.getEnclosingMethod());
}
}如果该类是在该方法中声明的本地类或匿名类,则getEnclosingMethod()方法返回该类的封闭方法,否则它将返回null。由于在上面的示例中,示例类是在方法getName()中声明的,它将返回输出
EnclosingMethod of Main: public java.lang.Object Main.getName()这意味着getName()方法的Main.class有一个本地类示例声明。如果getName()不像
public Object getName(){
return "A String";
}当未执行类声明时,getEnclosingMethod()将返回null。
编辑:正如@GhostCat所提到的,在这两个示例中,this.getClass().getMethods()[0].getName()将返回一个非空值,因为您基本上是在调用该方法。
发布于 2022-01-19 08:16:40
https://stackoverflow.com/questions/70767101
复制相似问题