Annotation in Java (2)

Below are the general guidelines to be followed while defining annotations:

  1. Annotation declaration should start with an ‘at’ sign like @, following with an interface keyword, following with the annotation name.
  2. Method declarations should not have any parameters.
  3. Method declarations should not have any throws clauses.
  4. Return types of the method should be one of the following:
    • primitives
    • String
    • Class
    • enum
    • array of the above types

There are specific annotations which can only be used in the context of annotations. The annotations are target, retention, documented and inherited.

Let’s look at their usage one at a time. First let’s look at target annotation. The target annotation defines which program elements can have annotations of the defined type. The user can put in the following options:

  1. TYPE: Class, interface, or enum (not annotation)
  2. FIELD: member fields (including enum values)
  3. METHOD: methods (does not include constrcutors)
  4. PARAMETER: method parameter
  5. CONSTRUCTOR: constructor
  6. LOCAL_VARIABLE: local variable or catch clause
  7. ANNOTATION_TYPE: Annotation types
  8. PACKAGE: java package

Annotaion Class(Person)

package annotation;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Person {
    String Gender();
    float Height() default 5.0f;
    float Weight() default 70.0f;    
}

TestClass

package annotation;


/**
 *
 * @author TaherT
 */
public class TestClass {
    
    @Person(Gender="MALE",Height=6.0f,Weight=75.0f)
    String taherTinwala;

    @Person(Gender="FEMALE",Height=5.0f,Weight=55.0f)
    String meeraKhan;
       
}
Advertisements
This entry was posted in Core JAVA. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s