0

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)
1

2 Answers 2

1

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);
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.