gpt4 book ai didi

Java 反射 : Code runs fine in Debugger but not in "normal" running mode

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:40:34 25 4
gpt4 key购买 nike

我正在尝试从方法数组中调用静态方法。这在调试器中工作得很好,但在正常运行模式下却不行。这是为什么?

下面的代码注释中有更多描述..

为了更容易重现而编辑,只需在调试器与正常模式下运行此类:

public class Stackoverflowquestion {

public static class Backautomat {
private String aktuellBackendeBrotsorte = "Butterbrot";
//Test für Statische Methoden: Brauche ich dazu auch eine Instanz für Invoke?
public static String getBezeichnung(){
return "Bezeichnung: Bester-Backautomat-Ever";
}
//Test für Methoden ohne Parameterliste
public boolean backautomat_starten(){
return true;
}
}

public static void main(String[] args) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException {
//Get all methods of class
Method[] backaudomadMethoden = Backautomat.class.getMethods();
//Get first Method of class -> I know this one is static -> see in source "Backautomat"
Method backMethod = backaudomadMethoden[0];
//Printing out Method Name: In Debugger this returns the static method name: getBezeichnung(),
//In "normal" running mode (Run -> Run as -> Java Application) it prints out the second method: backautomat_starten()
System.out.println(backMethod.getName());
//Invocation is successfull in debugger
//Invocation throws exception running in "normal" mode
System.out.println(String.valueOf(backMethod.invoke(null)));

}

EDIT 异常如下所示:

backautomat_starten Exception in thread "main" java.lang.NullPointerException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at com.relfection.easy.example.Stackoverflowquestion.main(Stackoverflowquestion.java:31)

最佳答案

考虑 documentation of Class.getMethods() :

The elements in the returned array are not sorted and are not in any particular order.

这意味着当前 JRE 的任意方面都可能具有改变结果的副作用,包括在调试器中运行。

因此,如果数组中的第一个方法不是您期望的方法,那么当尝试像 static 方法一样运行实例方法时,获得与预期不同的名称并产生异常,是以下症状同样错误的假设。

关于Java 反射 : Code runs fine in Debugger but not in "normal" running mode,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39874630/

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