How to create your own custom annotations in java and how to use it..PART-II

Hi in my previous post i have explained how to approach and understand over custom annotations using java, taking the support of meta annotations already given by java. Now i explain you how to code your own annotations. In my example i would like to explain how to inject object based on annotation.

Now i write a custom annotation “@AutoInject”, this annotation should be annotated on methods which will inject the object of particular class type as shown below

private EmployeeDTO employeeDTO;

public EmployeeDTO getEmployeeDTO() {
return employeeDTO;
}

@AutoInject
public void setEmployeeDTO(EmployeeDTO employeeDTO) {
this.employeeDTO = employeeDTO;
}

Now this code to get executed first we need to design our annotation i.e. @AutoInject as shown below:

/**
*
*/
package com.spark.custom.annotations;

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;

/**
* @author Mantha Pavan Kumar
* injects the object to a getter method
*/
@Documented
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface AutoInject {

}

Now to process the annotation we have to write a class which will actually give the annotation behavior as below.

/**
*
*/
package com.spark.custom.annotations;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.io.File;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;

/**
* @author Mantha Pavan Kumar
*
*/
public class GenericAnnotations {
/**
* @param obj
* @return
*/
public static <T> T injectDependencies(final T obj) {
try {
Class clazz = obj.getClass();
BeanInfo beanInfo = Introspector.getBeanInfo(clazz);

for (PropertyDescriptor pd : beanInfo.getPropertyDescriptors()) {
Method writeMethod = pd.getWriteMethod();

if (writeMethod == null) {
continue;
}

Object existingVal = pd.getReadMethod().invoke(obj);
if (existingVal == null) {
for (Annotation annotation : writeMethod.getAnnotations()) {
if (annotation instanceof AutoInject) {
Class propertyType = pd.getPropertyType();
writeMethod.invoke(obj, propertyType.newInstance());
}
}
}
}
} catch (Exception e) {
// do something intelligent :)
}
return obj;
}

}

in this way you can code your own functional behavior of annotations, Happy Coding 🙂 please find the below file for the entire code.
CustomAnnotations

Advertisements

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