Java Annotation无法正常工作方法错误

时间:2017-02-13 06:34:11

标签: java oop annotations

我正在开发一个注释,旨在强制一个类是不可变的。这里是处理器的代码:

最终输出显示错误

/*Exception in thread "main" java.lang.NullPointerException
at Annotation.Meta.myMeth(Meta.java:27)
at Annotation.Meta.main(Meta.java:34)8*/

import java.lang.annotation.Retention;
import java.lang.reflect.Method;

// An annotation type declaration.  
@Retention(RetentionPolicy.RUNTIME)


@interface MyAnno{

    String str();

int val();

}

class Meta {

    // Annotate a method.
    @MyAnno(str = "Annotation Example", val = 100)

    public static void myMeth() {
        Meta ob = new Meta();
        // Obtain the annotation for this method
        try {
            // First, get a Class object that represents
            Class< ? > c = ob.getClass();

            // Now, get a Method object that represents
            Method m = c.getMethod("myMeth");

            // Next, get the annotation for this class.
            MyAnno anno = m.getAnnotation(MyAnno.class);

            // Finally, display the values.
            System.out.println(anno.str() + " " + anno.val());

        }
        catch (NoSuchMethodException exc) {
            System.out.println("Method Not Found.");
        }

    }

    public static void main(String args[]) {
        myMeth();
    }
}

0 个答案:

没有答案