【发布时间】:2016-10-05 12:58:09
【问题描述】:
我正在尝试从方法数组中调用静态方法。这在调试器中工作得很好,但在正常运行模式下却不行。这是为什么呢?
下面的代码cmets中有更多描述..
编辑为了更容易复制只需在调试器与正常模式下运行这个类:
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)
【问题讨论】:
-
还有什么例外?您能否提供minimal reproducible example,以便我们自己复制它,而无需将不同的位复制并粘贴到不同的文件中? (我们应该能够创建一个新文件,复制、粘贴、编译、运行并查看错误。)
-
Class.getMethods()不提供任何保证顺序的方法。所以在调试器中运行可以对顺序产生影响。事实上,anything 可以对该顺序产生影响,但调试器的情况甚至是合理的…… -
来自
getMethods()的文档:“返回数组中的元素没有排序,也没有任何特定的顺序。” -
如果你想得到正确的方法,只需使用
Backautomat.class.getMethod("getBezeichnung")...
标签: java methods reflection nullpointerexception static