Friday, January 11, 2019

Java annotation – create/populate a bean object using annotation and reflection API


Java Annotation:


Annotations is a form of metadata for compiler/runtime environment. It provides data about a program. But it not a part of the program itself. Annotations do not have any impact on the operation of the code they annotate.

Annotations usage:

1)      Information for the compiler — Compilers can process annotation to detect error or as a hint to do some processing. E.g.

@Override method() indicates that the method() is overriding the implementation from the parent method(). Any mistake in signature can be detected by the compiler.

2)      Compile-time and deployment-time processing — A software tool can process annotation to generate new code, xml etc. E.g.

3)      Runtime processing — Annotation can be used at runtime to do meta-data based processing. E.g. getter/setter methods can be invoked on an object using annotations.


package com.bigdatacoder.examples;

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

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD) // can use in fields only.
public @interface MapElement {

   
public String id();
}

1 comment: