首页 > 解决方案 > Java Method.invoke 抛出 NullPointerException

问题描述

我正在进行一项开发,我应该通过 Method Reflect API 调用我的测试用例。目前,我可以调用该方法,也可以在调用特定方法后获取输出。但是在方法调用之后,invoke方法正在抛出NullPointerException。

我尝试添加一个 try 和 catch,以便我可以确切地知道我的代码的哪一部分正在抛出 NullException。根据我的观察,这段代码是这里的罪魁祸首。passed = (boolean) payload.invoke(testcase); 这是我用try and catch包围的代码:

public void execute() {
    try {
        Matcher m = Pattern.compile("([^()]*)[(]([^()]*)[)]").matcher(getPayloadString());
        m.find();
        boolean passed;
       
        if (m.group(2).isEmpty()) {
            System.out.println("m.group(2) is empty!!!!\n"); //This line of code is being executed. Because my argument is empty.
            passed = (boolean) payload.invoke(testcase);
            System.out.println("Boolean is: " + passed + "\n"); 
        }else {
            System.out.println("Inside else!!!\n");
            passed = (boolean) payload.invoke(testcase, ObjectCreator.convertParameters(m.group(2)));
            System.out.println("Boolean2 is: " + passed + "\n");

        }
        //If already invoked the method, this line should be executed. But now it didnt print out this debug message below.
        System.out.println("Already exited the convertParameters()\n");
        String output = passed ? "PASS" : "FAIL";
        TestCase.printResult(testcase.getClass().getName(), output, "", "", "");
    } catch (Exception ex) {
        System.out.println("Exception in execute is : " + ex.toString() + "\n");
    }
}

我不太确定它为什么会抛出 NULLPointerException。

标签: java

解决方案


推荐阅读