1

I am a newbie to annotations. I have gone through a lot of tutorials explaining the concept of annotations. But nowhere do i find information about defining multiple annotations within a class. So pls give me some insight on defining and accessing multiple annotations.Below is the code where I define two annotations in a class and eclipse IDE presents me an error "The public type SampleAnn must be defined in its own file".. Is the reason for this error because of the java convention that "there should only one public annotation per class in the name of the class-name"?

@Documented
@Target(ElementType.LOCAL_VARIABLE)
@Inherited
@Retention(RetentionPolicy.RUNTIME)
public @interface MethodInfo{
int number1;
}

@Documented
@Target(ElementType.LOCAL_VARIABLE)
@Retention(RetentionPolicy.RUNTIME)
public @interface SampleAnn{
int number2;
}
1
  • Annotations are classes, and you can't have more than one public top-level class per file in Java. Commented Nov 21, 2013 at 9:47

3 Answers 3

2

You are right, you can have only a single top-level class in one file.

But what you can do:

public class MyAnnotations {

   public @interface SampleAnn { ... }
   public @interface MethodInfo { ... }
}
Sign up to request clarification or add additional context in comments.

Comments

1

There should more generally be ONE public CLASS per class file and annotations are no exception. It is also important that any publicly defined entity has the same name as its java file's name, so I don't see how you could have two in the same file.

Comments

0

The annotations need to be in separate compilation units (files).

The regarding top-level classes the specification states:

This restriction implies that there must be at most one such type per compilation unit. This restriction makes it easy for a Java compiler to find a named class within a package. In practice, many programmers choose to put each class or interface type in its own compilation unit, whether or not it is public or is referred to by code in other compilation units.

Specification

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.