Java反射:代码在调试器中运行良好,但在“正常”运行模式下运行不正常

时间:2016-10-05 12:58:09

标签: java methods reflection nullpointerexception static

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

以下代码评论中的更多说明..

编辑以便于再现只需在调试器中运行此类与正常模式:

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)

2 个答案:

答案 0 :(得分:5)

考虑documentation of Class.getMethods()

  

...

     

返回数组中的元素没有排序,也没有任何特定的顺序。

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

因此,如果数组中的第一个方法不是您期望的那个,获取与预期不同的名称并在尝试像static方法一样运行实例方法时产生异常,则表示同样的错误假设

答案 1 :(得分:1)

https://docs.oracle.com/javase/7/docs/api/java/lang/reflect/Method.html#invoke(java.lang.Object,%20java.lang.Object...)

这表明您在传入的已定义对象

上调用该方法
String.valueOf(backMethod.invoke(null));

以下是传入null作为对象,因此您尝试在null对象上调用方法。

类似于做

之类的事情
Object x = null;
x.toString();

显然x.toString()会抛出NPE