【问题标题】:getEnclosingMethod() returning Null [duplicate]getEnclosureMethod() 返回 Null [重复]
【发布时间】:2022-01-19 08:02:25
【问题描述】:

我正在使用反射线记录函数名称

this.getClass().getEnclosingMethod().getName()

但它抛出 NULLPointerException 因为 this.getClass().getEnclosureMethod() 正在返回 Null,

虽然

this.getClass().getMethods()[0].getName() working fine.

为什么反射方法getEnclosureMethod()会抛出Null指针异常。 解决方法是什么

Java 版本:11

【问题讨论】:

  • 你为什么期望getEnclosingMethod返回null以外的东西?
  • 不乔,它没有回答,我问的是为什么这会返回 Null 而不是特定的 functionName this.getClass().getEnclosureMethod().getName() 我们不应该使用它吗?我
  • 哦,这很好地回答了你的问题。你的问题是你的假设是有缺陷的。所以,你不应该使用这个。提供给您的链接告诉您如何获取方法名称。
  • 并提示:答案确实在 javadocs 中。阅读这些方法的作用。最后:this.getClass().getMethods()[0].getName() working fine. 现在不是。这将始终返回该类的第一个方法的名称。它只是使用反射来获取该类的“静态”(不改变“)方法列表。尝试在具有多个方法的方法中使用它。令人惊讶的是,它不起作用。

标签: java


【解决方案1】:

我们先来了解一下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。由于在上面的示例中,Example Class 是在方法 getName() 中声明的,所以它会返回输出

EnclosingMethod of Main: public java.lang.Object Main.getName()

意思是 Main.class 的 getName() 方法声明了一个本地类 Example。 如果 getName() 不一样

public Object getName(){
        return "A String";
    }

getEnclosingMethod() 将返回 null,因为没有完成任何类声明。

编辑:正如@GhostCat 提到的,在这两个示例中this.getClass().getMethods()[0].getName() 将返回一个非空值,因为您基本上是在调用该方法。

【讨论】:

  • 您可能想要添加this.getClass().getMethods()[0].getName(),是的,确实返回了一个非空字符串。但是,这也不是 OP 想要的 ;-)
【解决方案2】:
  • 当且仅当此 Class 对象表示方法中的本地或匿名类时,它才返回表示底层类的直接封闭方法的 Method 对象
  • refer that

【讨论】:

    猜你喜欢
    • 2019-10-04
    • 2011-11-01
    • 2017-05-09
    • 2012-02-01
    • 2015-09-11
    • 2011-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多