sunleo
sunleo

Reputation: 10943

Exception in thread "main" java.lang.NoSuchMethodException:

Please help me to find why exception comes here.

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;
    }       

}

Exception :

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)

Upvotes: 0

Views: 3270

Answers (2)

Dici
Dici

Reputation: 25950

You used Integer.class whereas your method takes a int parameter, so you should use int.class instead.

Upvotes: 0

Mena
Mena

Reputation: 48404

You are passing an Integer class parameter.

You need to pass a primitive, as your method takes a primitive int.

Use:

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

Upvotes: 1

Related Questions