繁体   English   中英

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

[英]Exception in thread “main” java.lang.NoSuchMethodException:

请帮助我找到为什么异常发生在这里。

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)

您正在传递一个Integer类参数。

您需要传递一个原语,因为您的方法需要一个原语int

采用:

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM