Java annotation practical tutorials


  • Java Annotation is only for JDK5 or higher
  • Annotations are like meta-tags that you can add to your code and apply them to package declarations, type declarations, constructors, methods, fields, parameters, and variables.
  • Annotation-based development relieves Java developers from the pain of cumbersome configuration.
  • Simply speaking, annotation is a mechanism for associating a meta-tag with program elements and allowing the compiler or the VM to extract program behaviors from these annotated elements and generate interdependent codes when necessary.
  • There are two things you need to consider with annotations. One is the “annotation” itself; another is the “annotation type.”

When to use Annotation?

  • Replacing .properties and xml-config files: when annotations can be used in a clean and non-convoluted way as an alternative, for configuration information that is essentially part of the software and a deployment. Annotations are however an inappropriate replacement for configuration when it comes to configurations that may need to be changed dynamically during runtime.
  • Supporting cross-cutting concerns: I’d say annotations are in a way “aspect orientation, less the actual processing of aspects”. Annotations are an excellent way to do things like dependency injection, service discovery of managed objects, validation and many other similar things. Where ever aspect orientation could make sense, but you don’t want to go all out and actually use an aspect oriented language addition such as AspectJ, annotations could be a viable option

For details about Java Annotation, please refer here:

Practical [Download]

Create a validation annotation to validate class fields like email, phone, mobile, website format.

  1. Build annotation called ContactableValidator
    public @interface ContactableValidator {
    	public ContactableType type();
  2. Build Enum ContactableType
    public enum ContactableType {
  3. Build a class model called Customer
    public class Customer {
    	private String name;
    	private String phone;
    	private String mobilePhone;
    	private String website;
    	private String email;
    	private String address;
    	public String getName() {
    		return name;
    	public void setName(String name) { = name;
    	public String getPhone() {
    		return phone;
    	public void setPhone(String phone) { = phone;
    	public String getMobilePhone() {
    		return mobilePhone;
    	public void setMobilePhone(String mobilePhone) {
    		this.mobilePhone = mobilePhone;
    	public String getWebsite() {
    		return website;
    	public void setWebsite(String website) { = website;
    	public String getEmail() {
    		return email;
    	public void setEmail(String email) { = email;
    	public String getAddress() {
    		return address;
    	public void setAddress(String address) {
    		this.address = address;
  4. Create Validation Implementation Class to validate these fields
    public class ContactableValidationImpl {
    	 * Validate the email address
    	public static boolean isValidEmail(String email){
    		Pattern p = Pattern.compile(".+@.+\\.[a-z]+");
    		Matcher m = p.matcher(email);
    		return m.matches();
    	public static boolean isValidPhone(String phone){
    		Pattern p = Pattern.compile("\\d\\d([,\\s])?\\d\\d\\d\\d([,\\s])?\\d\\d\\d\\d");
    		Matcher m = p.matcher(phone);
    		return m.matches();
    	public static boolean isValidMobile(String mobile){
    		Pattern p = Pattern.compile("\\d\\d(\\d[,\\s])?\\d\\d\\d([,\\s])?\\d\\d\\d\\d");
    		Matcher m = p.matcher(mobile);
    		return m.matches();
    	public static boolean isValidWebsite(String website){
    		Pattern p = Pattern.compile("^(https?|ftp|file)://.+$");
    		Matcher m = p.matcher(website);
    		return m.matches();
  5. Create test class to validate these fields
    public class TestAnnotation {
    	 * @param args
    	 * @throws IllegalAccessException
    	 * @throws IllegalArgumentException
    	public static void main(String[] args) throws IllegalArgumentException, IllegalAccessException {
    		Customer customer = new Customer();
    		customer.setName("Tim Sturt");
    		customer.setPhone("09 1234 3819"); 			//correct phone format XX XXXX XXXX
    		customer.setMobilePhone("023 912 9123"); 	//correct mobile format XXX XXX XXXX
    		customer.setEmail("");		//correct email format
    		customer.setWebsite("");		//correct website url
    		Field [] fields = customer.getClass().getDeclaredFields();
    		for(Field field : fields){
    			Annotation [] annotations = field.getAnnotations();
    			for(Annotation annotation : annotations){
    				if(annotation instanceof ContactableValidator){
    					ContactableValidator validator = (ContactableValidator)annotation;
    					if(field.getModifiers() == Modifier.PRIVATE){
    					boolean result = false;
    						case PHONE:
    							result = ContactableValidationImpl.isValidPhone((String)field.get(customer));
    						case MOBILE:
    							result = ContactableValidationImpl.isValidMobile((String)field.get(customer));
    						case EMAIL:
    							result = ContactableValidationImpl.isValidEmail((String)field.get(customer));
    						case WEBSITE:
    							result = ContactableValidationImpl.isValidWebsite((String)field.get(customer));
    						System.out.println("Invalid " + field.getName() + ": " + field.get(customer));

1 Comment

Leave a Reply

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

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

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s