Monday, 30 June 2014

Simple Testing tool using Annotations

import java.lang.annotation.*;

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

public class TestClass {
    @Test public static void m1() { }
  
    public static void m2() { }
  
    @Test public static void m3() {
        throw new RuntimeException("Boom");
    }
  
    public static void m4() { }
  
    @Test public static void m5() { }
  
    public static void m6() { }
  
    @Test public static void m7() {
        throw new RuntimeException("Crash");
    }
  
    public static void m8() { }
}

import java.lang.reflect.*;

public class RunTests {
   public static void main(String[] args) throws Exception {
      int passed = 0, failed = 0;
      for (Method m : Class.forName(args[0]).getMethods()) {
         if (m.isAnnotationPresent(Test.class)) {
            try {
               m.invoke(null);
               passed++;
            } catch (Throwable ex) {
               System.out.printf("Test %s failed: %s %n", m, ex.getCause());
               failed++;
            }
         }
      }
      System.out.printf("Passed: %d, Failed %d%n", passed, failed);
   }
}

Compile all the java files.

Run the below command

java RunTests TestClass

Output
Test public static void TestClass.m3() failed: java.lang.RuntimeException: Boom

Test public static void TestClass.m7() failed: java.lang.RuntimeException: Crash

Passed: 2, Failed 2


Prevoius                                                 Next                                                 Home

@Documented

@Documented is a meta-annotation. You apply @Documented when defining an annotation, to ensure that classes using your annotation show this in their generated JavaDoc.

Example : Lets generate java doc for a java file using Annotations and using javadoc.

Using Documentation Comments
/**
 *  Author : Krishna
 *  Date : June 17th 2014
 *  Current Version : 1
 *  Last Modified : June 17th 2014
 *  Reviewers : Raghav
 */
public class SampleFile{

}
Run the below command
javadoc SampleFile.java.

You can get the documentation like below.

Using @Documented
import java.lang.annotation.*;

@Documented
public @interface AuthorDetails{
 String author();
 String date();
 int currentVersion() default 1;
 String lastModified() default "N/A";
 String[] Reviewers();
}

@AuthorDetails(
 author = "Krishna",
 date = "June 17th 2014",
 currentVersion = 1,
 lastModified = "June 17th 2014",
 Reviewers = {"Raghav", "Krishna"}
)
public class SampleFile{

}

Run the below command
javadoc SampleFile.java.

You can get the documentation like below.

Annotation @Documented is used to make the information in @AuthorDetails appear in Javadoc-generated documentation.



Prevoius                                                 Next                                                 Home

Sunday, 29 June 2014

@FunctionalInterface

A Functional interface is the one which has only one abstract method. The method declared in functional interface must not a public member of Object class.

The annotation type FunctionalInterface is used to indicate that an interface is meant to be a functional interface.

@FunctionalInterface
interface Interface1{
 Object getObject();
 int getABC();
}

When you tries to compile the above interface , compiler throws below error. Since Interface1 contains two abstract methods.

Interface1.java:1: error: Unexpected @FunctionalInterface annotation
@FunctionalInterface
^
  Interface1 is not a functional interface
    multiple non-overriding abstract methods found in interface Interface1
1 error

1. The following interface is not functional because it declares nothing which is not already a member of Object

@FunctionalInterface
 interface NonFunc {
 boolean equals(Object obj);
}

2. Below Program compiles fine. Since return types are covariantly equivalent, Interface2 Overrides the method in Interface1.
@FunctionalInterface
interface Interface1{
 Object getObject();
}

@FunctionalInterface
interface Interface2 extends Interface1{
 String getObject();
}

Related Links




Prevoius                                                 Next                                                 Home

@Repeatable

@Repeatable annotation, introduced in Java SE 8, indicates that the marked annotation can be applied more than once to the same declaration or type use.

It is much helpful when you have multiple fields declared in an annotation. For example:

@Repeatable
public @interface Role {
   String type;
   String[] allowed;
}

In this case, it is much easier to use this kind of annotation for multiple roles:

@Role(type="readonly", allowed={"view"})
@Role(type="admin", allowed={"view,add,update,delete"})
public boolean checkAllowed() {
}




Prevoius                                                 Next                                                 Home

@SafeVarargs

A variable arity parameter(Varargs) with a non-reifiable element type can cause heap pollution and give rise to compile-time unchecked warnings. Such warnings are uninformative if the body of the variable arity method is well behaved with respect to the variable arity parameter.

import java.util.*;
import java.lang.*;

class SafeVarargsEx{
 static void call(List<String>... stringLists) {
  String s = stringLists[0].get(0);
  System.out.println(s);
 }

 public static void main(String args[]){  
  List<String> myList1 = new ArrayList<> ();
  List<String> myList2 = new ArrayList<> ();
  
  myList1.add("Hi");
  myList2.add("Hi");
  
  call(myList1, myList2);
 }
}
When you tries to compile the above program, compiler throws below warning messages.

Note: SafeVarargsEx.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.

To suppress the above warnings use @SafeVarargs Annotation.

import java.util.*;
import java.lang.*;

class SafeVarargsEx{
 @SafeVarargs
 static void call(List<String>... stringLists) {
  String s = stringLists[0].get(0);
  System.out.println(s);
 }

 public static void main(String args[]){  
  List<String> myList1 = new ArrayList<> ();
  List<String> myList2 = new ArrayList<> ();
  
  myList1.add("Hi");
  myList2.add("Hi");
  
  call(myList1, myList2);
 }
}

Output
Hi

1. It is a compile-time error if a fixed arity method or constructor declaration is annotated with the annotation @SafeVarargs.

import java.util.*;
import java.lang.*;

class SafeVarargsEx1{
 @SafeVarargs
 static void call(List<String> stringLists) {
  String s = stringLists[0].get(0);
  System.out.println(s);
 }

 public static void main(String args[]){  
  List<String> myList1 = new ArrayList<> ();
 
  myList1.add("Hi");
  
  call(myList1);
 }
}

When you tries to compile the above program, compiler throws below error.

SafeVarargsEx1.java:6: error: Invalid SafeVarargs annotation. Method call(List<S
tring>) is not a varargs method.
        static void call(List<String> stringLists) {
                    ^
SafeVarargsEx1.java:7: error: array required, but List<String> found
                String s = stringLists[0].get(0);
                                      ^
2 errors

2. @SafeVarargs is only applicable to static methods, final instance methods, and constructors, the annotation is not usable where method overriding occurs.

import java.util.*;
import java.lang.*;

class SafeVarargsEx2{
 @SafeVarargs
 void call(List<String>... stringLists) {
  String s = stringLists[0].get(0);
  System.out.println(s);
 }
}

When you tries to compile the above program, compiler throws below error.

SafeVarargsEx2.java:6: error: Invalid SafeVarargs annotation. Instance method call(List<String>...) is not final.
        void call(List<String>... stringLists) {
             ^
1 error





Prevoius                                                 Next                                                 Home

@Deprecated

A program element annotated @Deprecated is one that programmers are discouraged from using, typically because it is dangerous, or because a better alternative exists.

A Java compiler produce a deprecation warning when a type, method, field, or constructor whose declaration is annotated with @Deprecated is used.

import java.util.*;

public class DeprecatedEx{    
 
 public static void main(String args[]){
  byte b[] = {1,2,3,4,5};
  String s  = new String(b, 3);
 }
}

When you tries to compile the above program, compiler throws below warning.  
Note: DeprecatedEx.java uses or overrides a deprecated API.
Note: Recompile with -Xlint:deprecation for details.

Since program used the deprecated String Constructor.

You can suppress the compiler warnings by @SuppressWarnings Annotation.

1. Use of the @Deprecated annotation on a local variable declaration or on a parameter declaration has no effect.



Prevoius                                                 Next                                                 Home

Friday, 27 June 2014

@SuppressWarnings

It is an annotation to suppress compile warnings that are generated by Compiler. If you want to suppress a warning in a particular method, you should annotate that method rather than its class.

Example
import java.util.*;

public class SuppressEx{    
 
 public static void main(String args[]){
  byte b[] = {1,2,3,4,5};
  String s  = new String(b, 3);
 }
}

When you tries to compile the above program, compiler shows below warnings.

Note: SuppressEx.java uses or overrides a deprecated API.
Note: Recompile with -Xlint:deprecation for details.

To suppress the warnings change the class file like below.

import java.util.*;

public class SuppressEx{    
 @SuppressWarnings("deprecation")
 public static void main(String args[]){
  byte b[] = {1,2,3,4,5};
  String s  = new String(b, 3);
 }
}

Prevoius                                                 Next                                                 Home

@Override

If a method declaration is annotated with the annotation @Override, but the method does not override or implement a method declared in a supertype, or is not override equivalent to a public method of Object, a compile-time error occurs.

Use it every time you override a method to detect bugs early.

For Example
public class SuperClass {
 public void print(){
 
 }
}

import java.lang.annotation.Annotation;

public class SubClass extends SuperClass{    
 @Override
    public void Print(){
 
 }
}

When you tries to compile the above program below error thrown.

SubClass.java:4: error: method does not override or implement a method from a supertype
        @Override
        ^
1 error

Since Print method in SubClass.java actually not overriding the method in SuperClass.java. Becaue the method Print in SubClass.java starts with Capital 'P' where as SuperClass.java starts with small 'p'.

Now change the method name in SubClass.java and recompile.

import java.lang.annotation.Annotation;

public class SubClass extends SuperClass{    
 @Override
    public void print(){
 
 }
} 




Prevoius                                                 Next                                                 Home

@Inherited

It is used to indicate that annotations on a class C corresponding to a given annotation type are inherited by subclasses of C.

Running without Inherited Annotation
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation1{
    String value();
}

@MyAnnotation1("abcd")
public class SuperClass {

}

import java.lang.annotation.Annotation;

public class SubClass extends SuperClass{    
    public static void main(String args[]){
        Class myClass = SubClass.class;
        Annotation ann[] = myClass.getAnnotations();
        for(int i=0; i< ann.length; i++){
            System.out.println(ann[i].toString());
        }
    }
}

Output prints nothing. Now try to add @Inherited Annotation to MyAnnotation1 and re compile and run the SubClass.java.

Running with Inherited Annotation 
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

@Retention(RetentionPolicy.RUNTIME)
@Inherited
public @interface MyAnnotation1{
    String value();
} 


Output

@MyAnnotation1(value=abcd)




Prevoius                                                 Next                                                 Home

RetentionPolicy.RUNTIME

RetentionPolicy.RUNTIME: The marked annotation is retained by the JVM so it can be used by the runtime environment.

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

@Retention(RetentionPolicy.SOURCE)
@interface MyAnnotation1{
    String value();
}

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

@Retention(RetentionPolicy.CLASS)
@interface MyAnnotation2{
    String value();
}

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

@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation3{
    String value();
}

import java.lang.annotation.*;

@MyAnnotation1("Using MyAnnotation1")
@MyAnnotation2("Using MyAnnotation2")
@MyAnnotation3("Using MyAnnotation3")
public class RetainEx {
    public static void main(String args[]){
        Class myClass = RetainEx.class;
        Annotation ann[] = myClass.getDeclaredAnnotations();
        
        for(int i=0; i< ann.length; i++){
            System.out.println(ann[i].toString());
        }
    }
}

Output
@annotations.MyAnnotation3(value=Using MyAnnotation3)




Prevoius                                                 Next                                                 Home

RetentionPolicy.CLASS

RetentionPolicy.CLASS : The marked annotation is retained by the compiler at compile time, but is ignored by the Java Virtual Machine (JVM). Annotations are to be recorded in the class file by the compiler but need not be retained by the VM at run time.

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

@Retention(RetentionPolicy.CLASS)
@interface MyAnnotation2{
    String value();
}



Prevoius                                                 Next                                                 Home

RetentionPolicy.SOURCE

RetentionPolicy.SOURCE: The marked annotation is retained only in the source level and is ignored by the compiler. i.e. these are discarded during the compilation. These annotations don't make any sense after the compilation, so they aren't written to the bytecode.

Things like @SuppressWarnings, @Override are annotations used by the compiler not needed at runtime. For those RetentionPolicy.SOURCE would make sense.

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

@Retention(RetentionPolicy.SOURCE)
@interface MyAnnotation1{
    String value();
}



Prevoius                                                 Next                                                 Home

@Retention

@Retention annotation specifies how the marked annotation is stored.
  1. RetentionPolicy.SOURCE – The marked annotation is retained only in the source level and is ignored by the compiler.
  2. RetentionPolicy.CLASS – The marked annotation is retained by the compiler at compile time, but is ignored by the Java Virtual Machine (JVM).
  3. RetentionPolicy.RUNTIME – The marked annotation is retained by the JVM so it can be used by the runtime environment.

Prevoius                                                 Next                                                 Home