hello world-java annotations


Java annotation is a good concept to implement while you designing a large application in order to reduce the maintenance overhead. Some of the use cases like,
1. Code generation automatically
2. Initialize some of the variables or your caching system while staring the application.
3. Define the life cycle of your application and make sure your code running after all the life cycle of your framework.

Step 1:
Create an interface and add the code like below.

package com.test;

import java.lang.annotation.*;


@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface FirstAnnotations {
	
}

Note the interface keyword, you should add “@” to mark it as annotation.

Then Let us create an Annotation implementation class like below.

package com.test;
public class AnnoImplementation {
	@FirstAnnotations()	
	public static void callMe() {		
		System.out.println("test");
		
	}

}

while all set all we need to call the annotation like below.

package com.test;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class CallAnno {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		try {
			for(Method m: Class.forName("com.test.AnnoImplementation").getMethods()) {
				
				
				
				if(m.isAnnotationPresent(FirstAnnotations.class)) {
					//System.out.println("called");
					//m.invoke(null);
					try {
						System.out.println(m.getName());
						m.invoke(null);
					} catch (IllegalArgumentException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (IllegalAccessException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (InvocationTargetException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		} catch (SecurityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		

	}

}

Advertisements

One thought on “hello world-java annotations

Leave a Reply

Please log in using one of these methods to post your comment:

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