Getting java.lang.NullPointerException when calling Method.invoke

前端 未结 4 1184
耶瑟儿~
耶瑟儿~ 2021-02-19 11:17

I\'m following this tutorial on Java annotaitons and implemented the Test annotation as shown there. But when running the code I get the following output.

java.l         


        
4条回答
  •  梦毁少年i
    2021-02-19 12:06

    The parameter that you pass to invoke must be an object on which the method is invoked, unless the method is static. What you did through reflection is equivalent to this:

    MyTest obj = null;
    obj.testBlah();
    

    Naturally, there's an NPE. To fix this problem, pass an object on which to invoke the method, or make the method static.

    Here is one way to make a fix:

    public  void parse(Class clazz, T obj) throws Exception {
        Method[] methods = clazz.getMethods();
        int pass = 0;
        int fail = 0;
    
        for (Method method : methods) {
            if (method.isAnnotationPresent(Test.class)) {
                Test test = method.getAnnotation(Test.class);
                Class expected = test.expected();
                try {
                    method.invoke(obj);
                    pass++;
                } catch (Exception e) {
                    if (Exception.class != expected) {
                        e.printStackTrace();
                        fail++;
                    } else {
                        pass++;
                    }
                }
            }
        }
        System.out.println("Passed:" + pass + "   Fail:" + fail);
    }
    
    ...
    
    parser.parse(MyTest.class, new MyTest());
    

    Demo on ideone.

提交回复
热议问题