title: Getting java.lang.NullPointerException when calling Method.invoke
body: <p>I'm following this <a href="http://isagoksu.com/2009/development/java/creating-custom-annotations-and-making-use-of-them/" rel="noreferrer">tutorial on Java annotaitons</a> and implemented the Test annotation as shown there. But when running the code I get the following output.</p>
  
  <pre><code>java.lang.NullPointerException
      at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
      at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
      at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
      at java.lang.reflect.Method.invoke(Method.java:616)
      at TestAnnotationParser.parse(Demo.java:24)
      at Demo.main(Demo.java:51)
  Passed:0   Fail:1
  </code></pre>
  
  <p>Following is my code. Can someone point out what I have got wrong?</p>
  
  <pre><code>import java.lang.annotation.ElementType;
  import java.lang.annotation.Retention;
  import java.lang.annotation.RetentionPolicy;
  import java.lang.annotation.Target;
  import java.lang.reflect.Method;
  
  @Target(ElementType.METHOD)
  @Retention(RetentionPolicy.RUNTIME)
  @interface Test {
      Class expected();
  }
  
  class TestAnnotationParser {
      public void parse(Class&lt;?&gt; clazz) 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(null);
                      pass++;
                  } catch (Exception e) {
                      if (Exception.class != expected) {
                          e.printStackTrace();
                          fail++;
                      } else {
                          pass++;
                      }
                  }
              }
          }
          System.out.println("Passed:" + pass + "   Fail:" + fail);
      }
  }
  
  class MyTest {
  
      @Test(expected = RuntimeException.class)
      public void testBlah() {
      }
  }
  
  public class Demo {
      public static void main(String[] args) {
          TestAnnotationParser parser = new TestAnnotationParser();
          try {
              parser.parse(MyTest.class);
          } catch (Exception e) {
              e.printStackTrace();
          }
      }
  }
  </code></pre>