web
 

Java Annotations – Annotations in Java


Annotations in java give data about the code. Java explanations have no immediate impact on the code they explain. In java comments instructional exercise, we will investigate following;

  1. see worked in Java explanation example
  2. how to compose custom annotation
  3. comments use and how to parse comments utilizing reflection

    Java Annotations

    java comments, comments in java, java comment model, java comments instructional exercise, java custom comment

    Annotations are presented in Java 1.5 and now it's intensely utilized in Java EE systems like Hibernate,Jersey, Spring.

    Java Annotation is metadata about the program implanted in the program itself. It tends to be parsed by the comment parsing device or by compiler. We can likewise indicate explanation accessibility to either assemble time just or till runtime also.

    Before java comments, program metadata was accessible through java remarks or by javadoc yet explanation offers more than that. Explanations metadata can be accessible at runtime as well and comment parsers can utilize it to decide the procedure stream.

    Java Custom Annotation

    Creating custom explanation in java is like composition an interface, then again, actually it interface catchphrase is prefixed with @ image. We can pronounce techniques in explanation.

    Let's see java custom comment precedent and after that we will talk about it's highlights and essential points.

    
    package com.journaldev.annotations;
    
    import java.lang.annotation.Documented;
    import java.lang.annotation.ElementType;
    import java.lang.annotation.Inherited;
    import java.lang.annotation.Retention;
    import java.lang.annotation.RetentionPolicy;
    import java.lang.annotation.Target;
    
    @Documented
    @Target(ElementType.METHOD)
    @Inherited
    @Retention(RetentionPolicy.RUNTIME)
    public @interface MethodInfo{
    	String author() default "Pankaj";
    	String date();
    	int revision() default 1;
    	String comments();
    }
    

    Some imperative focuses about java comments are:

    1. Annotation strategies can't have parameters.
    2. Annotation strategies return types are constrained to natives, String, Enums, Annotation or exhibit of these.
    3. Java Annotation strategies can have default values.
    4. Annotations can have meta explanations appended to them. Meta explanations are utilized to give data about the annotation.

      Meta comments in java

      There are four sorts of meta annotations:

      1. @Documented – demonstrates that components utilizing this comment ought to be recorded by javadoc and comparable devices. This sort ought to be utilized to comment on the presentations of sorts whose comments influence the utilization of clarified components by their customers. On the off chance that a sort presentation is commented on with Documented, its comments turn out to be a piece of the open API of the clarified elements.
      2. @Target – demonstrates the sorts of program component to which an explanation type is material. Some conceivable qualities are TYPE, METHOD, CONSTRUCTOR, FIELD and so forth. In the event that Target meta-comment is absent, at that point comment can be utilized on any program element.
      3. @Inherited – demonstrates that an explanation type is consequently acquired. In the event that client inquiries the explanation type on a class announcement, and the class assertion has no comment for this sort, at that point the class' superclass will naturally be questioned for the comment type. This procedure will be rehashed until a comment for this sort is found, or the highest point of the class progression (Object) is reached.
      4. @Retention – shows to what extent comments with the explained sort are to be held. It takes RetentionPolicy contention whose Possible qualities are SOURCE, CLASS and RUNTIME

    Built-in explanations in Java

    Java Provides three implicit annotations.

    1. @Override – When we need to abrogate a technique for Superclass, we should utilize this explanation to educate compiler that we are superseding a strategy. So when superclass strategy is evacuated or changed, compiler will demonstrate blunder message. Realize why we ought to dependably utilize java abrogate comment while superseding a method.
    2. @Deprecated – when we need the compiler to realize that a technique is belittled, we should utilize this explanation. Java suggests that in javadoc, we ought to give data to why this strategy is censured and what is the option to use.
    3. @SuppressWarnings – This is simply to advise compiler to disregard explicit admonitions they produce, for instance utilizing crude sorts in java generics. It's maintenance arrangement is SOURCE and it gets disposed of by compiler.
    Java Annotations Example

    Let's see a java model appearing of implicit explanations in java just as utilization of custom comment made by us in above example.

     
    
    package com.journaldev.annotations;
    
    import java.io.FileNotFoundException;
    import java.util.ArrayList;
    import java.util.List;
    
    public class AnnotationExample {
    
    	public static void main(String[] args) {
    	}
    
    	@Override
    	@MethodInfo(author = "Pankaj", comments = "Main method", date = "Nov 17 2012", revision = 1)
    	public String toString() {
    		return "Overriden toString method";
    	}
    
    	@Deprecated
    	@MethodInfo(comments = "deprecated method", date = "Nov 17 2012")
    	public static void oldMethod() {
    		System.out.println("old method, don't use it.");
    	}
    
    	@SuppressWarnings({ "unchecked", "deprecation" })
    	@MethodInfo(author = "Pankaj", comments = "Main method", date = "Nov 17 2012", revision = 10)
    	public static void genericsTest() throws FileNotFoundException {
    		List l = new ArrayList();
    		l.add("abc");
    		oldMethod();
    	}
    
    }
    

    I believe above java annotation example is self explanatory and showing use of annotations in different cases.

    Java Annotations Parsing

    We will use Reflection to parse java annotations from a class. Please note that Annotation Retention Policy should be RUNTIME otherwise it’s information will not be available at runtime and we wont be able to fetch any data from it.

    
    package com.journaldev.annotations;
    
    import java.lang.annotation.Annotation;
    import java.lang.reflect.Method;
    
    public class AnnotationParsing {
    
    	public static void main(String[] args) {
    		try {
    			for (Method method : AnnotationParsing.class.getClassLoader()
    					.loadClass(("com.journaldev.annotations.AnnotationExample")).getMethods()) {
    				// checks if MethodInfo annotation is present for the method
    				if (method.isAnnotationPresent(com.journaldev.annotations.MethodInfo.class)) {
    					try {
    						// iterates all the annotations available in the method
    						for (Annotation anno : method.getDeclaredAnnotations()) {
    							System.out.println("Annotation in Method '" + method + "' : " + anno);
    						}
    						MethodInfo methodAnno = method.getAnnotation(MethodInfo.class);
    						if (methodAnno.revision() == 1) {
    							System.out.println("Method with revision no 1 = " + method);
    						}
    
    					} catch (Throwable ex) {
    						ex.printStackTrace();
    					}
    				}
    			}
    		} catch (SecurityException | ClassNotFoundException e) {
    			e.printStackTrace();
    		}
    	}
    
    }
    

    Output of the above program is:

     
    
    Explanation in Method 'public java.lang.String com.journaldev.annotations.AnnotationExample.toString()' : @com.journaldev.annotations.MethodInfo(author=Pankaj, revision=1, comments=Main strategy, date=Nov 17 2012) 
    
    Technique with correction no 1 = open java.lang.String com.journaldev.annotations.AnnotationExample.toString() 
    
    Explanation in Method 'public static void com.journaldev.annotations.AnnotationExample.oldMethod()' : @java.lang.Deprecated() 
    
    Explanation in Method 'public static void com.journaldev.annotations.AnnotationExample.oldMethod()' : @com.journaldev.annotations.MethodInfo(author=Pankaj, revision=1, comments=deprecated strategy, date=Nov 17 2012) 
    
    Technique with correction no 1 = open static void com.journaldev.annotations.AnnotationExample.oldMethod() 
    
    Explanation in Method 'public static void com.journaldev.annotations.AnnotationExample.genericsTest() tosses java.io.FileNotFoundException' : @com.journaldev.annotations.MethodInfo(author=Pankaj, revision=10, comments=Main strategy, date=Nov 17 2012) 
    
    

    Reflection API is extremely amazing and utilized generally in Java, J2EE systems like Spring, Hibernate, JUnit, look at Reflection in Java.

    That's in support of the java comments model instructional exercise, I trust you took in something from it.






journaldev is optimized for learning.© journaldev .
All Right Reserved and you agree to have read and accepted our term and condition