线程“main”java.lang.NoSuchMethodException中的异常:

时间:2014-08-01 10:44:57

标签: java annotations

请帮我找一下为什么有例外。

public class SampleAnnotation
{
    public static void main(String args[]) throws Exception
    {

        Method method = Check.class.getDeclaredMethod("getId", null);
        System.out.println("method:"+method);
        SampleAnnotation1 annotMethd = method.getAnnotation(SampleAnnotation1.class);
        System.out.println(annotMethd.author()+"::"+annotMethd.lastModified());

        method = Check.class.getDeclaredMethod("getId", Integer.class);
        System.out.println("method:"+method);
        annotMethd = method.getAnnotation(SampleAnnotation1.class);
        System.out.println(annotMethd.author()+"::"+annotMethd.lastModified());


    }
}

@Documented
@Retention(value=RetentionPolicy.RUNTIME)
@Target(value={ElementType.CONSTRUCTOR,ElementType.FIELD,ElementType.LOCAL_VARIABLE,ElementType.METHOD,ElementType.PACKAGE,ElementType.PARAMETER,ElementType.TYPE})
@interface SampleAnnotation1 
    {
           String author();
           String lastModified() default "N/A";        

    }
@SampleAnnotation1
( author = "leo",  
  lastModified = "joe"
  )
class Check
{
    @SampleAnnotation1
    ( 
            author = "joe"          
    )
    public int id;

    @SampleAnnotation1
    ( 
            author = "joeidgetter"
    )
    public int getId() {
        return id;
    }
    @SampleAnnotation1
    ( 
            author = "joeidgetterwithint"
    )
    public int getId(int i) {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }       

}

例外:

method:public int leo.annotate.Check.getId()
joeidgetter::N/A
Exception in thread "main" java.lang.NoSuchMethodException: leo.annotate.Check.getId(java.lang.Integer)
    at java.lang.Class.getDeclaredMethod(Unknown Source)
    at leo.annotate.SampleAnnotation.main(SampleAnnotation.java:20)

2 个答案:

答案 0 :(得分:1)

您正在传递Integer类参数。

您需要传递基元,因为您的方法采用原始int

使用:

method = Check.class.getDeclaredMethod("getId", int.class);

答案 1 :(得分:0)

您使用了Integer.class,而您的方法使用int参数,因此您应该使用int.class