Java Annotations

AOP in Java Using Annotation

Java is one of my favorite languages. It is simple. But some of its features are still not used very commonly. One of them is Annotations. Annotation is very simple and one of the powerful concept of java. If you have worked the on framework like spring , you may have seen there are Annotation to do most of the setting.

Though we have used annotation in many ways , still I have not seen my developer going for the creation of their custom annotation. This blog helps us to understand when and where we can utilize the power of annotation.

What is Annotation?

import javax.annotation.PostConstruct;
import javax.validation.constraints.Max;

@Deprecated
public class Foo {

@Max(10)
int foo = 0;

@PostConstruct
private void setFoo() {
foo = 4;
}
@Deprecated
int returnFooCount() {
return foo;
}
}

Annotation is a tag which can have metadata that can be attached to class, interface, methods or fields to indicate some additional information which can be used by Java compiler and JVM.

Example:- @Deprecated,@Override,@PostConstruct are some of the in build java annotation which we have been using.Here you have seen we have added the annotation at class , at attribute and even at method.

Why Annotations?

Prior to Annotations, XML was often used to have the metadata. The Large set of Architectures and developers often believe that XML maintenance is difficult and it is not very easy to read. Something was needed which should be more close to code.Annotations are easy to understand and more readable.

Uses Of Annotations

  • Information for the compiler — Annotations can be used by the compiler to detect errors or suppress warnings or to give some information to the compiler.[eg- @Serialization]
  • Compile-time and deployment-time processing — Software tools can process annotation information to generate code, XML files, and so forth.[eg -lombok project – @Data,@Builder]
  • Runtime processing — Some annotations are available to be examined at runtime.[ It can be used as point cut in Aspect Oriented Programming]
  • Comments — Often people use annotation to provide comments, why I prefer annotations over the comment as it provides the structural way of commenting.[@Deprecated, any other custom annotation]

How Annotation Works?

Before using any concept we should understand how it works internally, only then we can explore the better way of using it and can use it properly.As we all know annotation does not contain any business knowledge.Then how it actually works?

When Java source code is compiled, annotations can be processed by compiler plug-ins called annotation processors. Processors can produce informational messages or create additional Java source files or resources, which in turn may be compiled and processed, and also modify the annotated code itself. The Java compiler conditionally stores annotation metadata in the class files, if the annotation has a RetentionPolicy of CLASS or RUNTIME(We will cover more about retention policy in further section). Later, the JVM or other programs can look for the metadata to determine how to interact with the program elements or change their behavior.

In addition to processing an annotation using an annotation processor, a Java programmer can write their own code that uses reflections to process the annotation

This package contains the interface called AnnotatedElement that is implemented by the Java reflection classes including Class, Constructor, Field, Method, and Package. The implementations of this interface are used to represent an annotated element of the program currently running in the Java Virtual Machine. This interface allows annotations to be read reflectively.

The AnnotatedElement interface provides access to annotations having RUNTIME retention. This access is provided by the getAnnotation, getAnnotations, and isAnnotationPresentmethods. Because annotation types are compiled and stored in byte code files just like classes, the annotations returned by these methods can be queried just like any regular Java object.

How to Build Custom Annotation?

Below is the simplest Annotation one can create.


public @interface CustomAnnotation {
}

 

Annotations itself can have some annotations, which tell us something about our new annotation.

  • Retention – It tells java how long any annotation will be retained during the different phase of code. Retention annotation have property RetentionPolicy which have 3 possible values:-
    • Source: Annotations are to be discarded by the compiler.
    • Class: Annotations are to be recorded in the class file by the compiler but need not be retained by the VM at run time.[DEFAULT]
    • Runtime: Annotations are to be recorded in the class file by the compiler and retained by the VM at run time so they may be read reflectively.

@Retention(RetentionPolicy.RUNTIME)
public @interface CustomAnnotation {
}

Note-A Retention meta-annotation has effect only if the meta-annotated type is used directly for annotation. It has no effect if the meta-annotated type is used as a member type in another annotation type.

  • Target: As we know we can put annotation at many different levels, at class, at attribute and many other. But as a developer, you might want to bound the use of your annotation at some level only, as your annotation can make sense some particular level.To declare the level this annotation is used.It has an attribute array of element type which can have all the possible level. There are different type elements in java.Most of them are self-explanatory.
    • Element Type
      • TYPE
      • FIELD
      • METHOD
      • PARAMETER
      • CONSTRUCTOR
      • LOCAL_VARIABLE
      • ANNOTATION_TYPE
      • PACKAGE
      • TYPE_PARAMETER [new in java 1.8]
        • eg  <T extends @A Object & @B Comparable, U extends @C Cloneable>
      • TYPE_USE [new in java 1.8] eg –
        • Map<@NonNull String, @NonEmpty List<@Readonly Document>> files;
  • Inherited:- If this annotation is present it will be inherited to the subclass, By default it is not present. It will only be effective when the annotation is given at class level.
  • Documented:-  Marks the annotation for inclusion in the documentation. Indicates that annotations with a type are to be documented by javadoc and similar tools by default.
  • Repeatable: Prior to Java 8 user were not allowed to give same anntation multiple times at same place.But If any annotation have repeatable annotation that can be put multiple time at same place.

Example

 

@Retention( RetentionPolicy.RUNTIME )
public @interface Cars {
       Manufacturer[] value() default{};
 }

@Repeatable(value = Cars.class )
public @interface Manufacturer {
String value();
};

@Manufacturer( "Mercedes Benz")
@Manufacturer( "Toyota")
@Manufacturer( "BMW")
@Manufacturer( "Range Rover")
public interface Car { 

}

Now we can give Manufacturer annotation multiple times to interface Car. Manufacturer annotation contains the Repeatable annotation which contains some other annotation as its value.

 

 

Now we know all the attribute of annotation, we can create annotations.


@Retention(RetentionPolicy.RUNTIME)
@Documented
@Target(value = {ElementType.TYPE})
public @interface CustomAnnotation {
String name();
String identifier() default "";
}

 

In our custom annotation, we have two properties name and identifier. A value doesn’t have any default property, so whenever we use this  CustomAnnotation it is mandated to give value attribute some value, otherwise, it gives error.On the other hand, identifier contain some default value, so we don’t have to compulsory give its value.

 

So, till now we have some basic idea how annotation work, and how to create an annotation.In the further blog, we will see the different situations where we can create our own custom annotations, and how to tell JVM to process these annotations.

Some Useful In-Build Annotations in Java

 

  • @GuardedBy
  • @Immutable
  • @NotThreadSafe
  • @ThreadSafe
  • @SuppressWarnings

Some Uses on Annotations

 


Useful Links

Advertisements

Difference between Dependency Management and Dependencies in Maven

Maven is a software management tool, use to manage information, dependencies and other things for a project.

It has two mechanisms to add the dependencies of other modules/project. One is Dependencies tag and other is Dependency Managment. People often wonder whats a difference between the two. An important question is when to use what?

First, of all, we should have an idea of what is multi module applications.As in the case in case of multi module applications only they differ.

A multi-module project is, as its name suggests, a project that consists of multiple modules, where a module is a project. You can think of a multi-module project as a logical grouping of sub-projects. The packaging of a multi-module project is “pom” since it consists of a pom.xml file but no artifact (jar, war, ear, etc).

multimodule-web-spring_projects

That’s a technical story. But it is not great if we are trying to teach some one. As concepts should be as simple as a story for a 12-year-old child. So let’s understand dependencies and dependency management.

There is a man called Peter, he has two ice cream parlors, Gelatos, and Baskin Robbins. Peter has two children Ron and Seria.

Peter has 2 ice cream in gelatos ice cream parlor – mango[ basic version ] and straberry[ moderate version] and 1 ice cream in Baskin Robbins – black current[high version].

Both Ron and Seria can have all the ice creams which their father has in Gelatos parlor, but they can have ice from Baskin Robbins only if they ask for it.Which means they can only have black current if they ask for specific it, but they don’t have to mention which version of black current they need, as their father Peter already know which kind of black current ice we have.

Here Peter is parent module and,  Ron and Seria are child modules.Gelatos is dependencies tag and Baskin Robin is Dependency Management tag.

screen-shot-2015-06-28-at-18-18-31-480x275

So all the dependencies present in dependencies tag will be available to all its child modules.But all the dependencies present in dependency management of parent module will be available to the child only if those dependencies are declared in dependencies tag of child module.

So why are we even using dependency management if dependencies tag passes all the dependency to its children?

  1. As all the children might not need all the dependencies present in parent module, so it is always wise to use Dependency Managment.
  2. Using Dependency Managment we can create a consistency of which version and tag of any artifact which we are using through out the application.[It help to maintain the version of artifact]
  3. Dependency Managment manage version, scope, and exclusion of artifact in child modules.

Example –

Parent POM- A

</pre>
<pre><?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns="http://maven.apache.org/POM/4.0.0"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.test</groupId>
    <artifactId>A</artifactId>
    <packaging>pom</packaging>
    <version>1.0-SNAPSHOT</version>
    <modules>
        <module>B</module>
        <module>C</module>
    </modules>

    <dependencies>
            <dependency>
            <groupId>com.external</groupId>
            <artifactId>d1</artifactId>
            <version>1</version>
        </dependency>
    </dependencies>
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>com.external</groupId>
                <artifactId>d2</artifactId>
                <version>1</version>
            </dependency>
            <dependency>
                <groupId>com.external</groupId>
                <artifactId>d3</artifactId>
                <version>1</version>
            </dependency>
        </dependencies>

    </dependencyManagement>
</project></pre>
<pre>

It has 2 child module A and B. Parent A has 3 dependencies in total:-

  • d1 [Inside dependencies tag]
  • d2 [Inside dependency management tag]
  • d3 [Inside dependency management tag]

 

 Child Pom B

</pre>
<pre><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <groupId>com.test</groupId>
        <artifactId>A</artifactId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.test</groupId>
    <artifactId>B</artifactId>
    <packaging>pom</packaging>

    <dependencies>
        <dependency>
            <groupId>com.external</groupId>
            <artifactId>d2</artifactId>
        </dependency>
        <dependency>
            <groupId>com.external</groupId>
            <artifactId>d4</artifactId>
            <version>1</version>
        </dependency>
    </dependencies>
</project></pre>
<pre>

It will have access to 3 artifacts

  • d1 [coming from dependencies of parent ]
  • d2 [coming from  parent dependency management as mention in its dependencies tag]
  • d4 [coming from its dependencies tag]

Note:- It will not have the d3 artifact, as d3 is mention dependency management tag of parent pom [POM A] but not present in child pom [POM B].

Child Pom C

</pre>
<pre><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <groupId>com.test</groupId>
        <artifactId>A</artifactId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.test</groupId>
    <artifactId>C</artifactId>
    <packaging>pom</packaging>

    <dependencies>
        <dependency>
            <groupId>com.external</groupId>
            <artifactId>d3</artifactId>
        </dependency>
        <dependency>
            <groupId>com.external</groupId>
            <artifactId>d5</artifactId>
            <version>1</version>
        </dependency>
    </dependencies>
</project></pre>
<pre>

Similarly, It will have access to 3 artifacts

  • d1 [coming from dependencies of parent ]
  • d3 [coming from  parent dependency management as mention in its dependencies tag]
  • d5 [coming from its dependencies tag]

Note:- It will not have the d3 artifact, as d3 is mention dependency management tag of parent pom [POM A] but not present in child pom [POM B].


 

Further Reading – http://maven.apache.org/guides/introduction/introduction-to-dependency-mechanism.html

 

Given an array of characters, find the longest continuous non-repeating sequence of characters

Ex: aabcdefdghiajk – efdghiajk

 

char[] str = {‘a’,’a’,’b’,’c’,’d’,’e’,’f’,’d’,’g’,’h’,’i’,’a’,’j’,’k’};
int len = str.length;
System.out.println(“len “+len);
Map m = new LinkedHashMap();

for (int i = 0; i < len; i++) {
System.out.println(str[i]+” “+i);
if(m.containsKey(str[i])){
System.out.println(“found”);
i = (int) m.get(str[i]);
System.out.println(“new i”+i);

m.clear();
}else{

m.put(str[i], i);
}

}

Check If tree is a Binary Search Tree

Hi , this post is to find if tree is the binary search tree or not.

Common approach

Check for each root , right child should be large , and left child should be small.

but , this is not a correct approach.

It can show wrong result , for more understanding read from the URL given below.

Correct Approach

1. Perform a In order Traversal of a given tree and store the result in the array.

Code Snippet:

Create ArrayList arrayList

InorderTraversal(Node n){

if(n != null){

InorderTraversal(n.leftChild);

arrayList.add(n.value);

InorderTraversal(n.rightChild);

}

}

}

2.Now check the array show be in ascending order, if it is not in ascending order than the tree it is  not a Binary search Tree.

Now we have and arrayList we can perform the following action to get the final result.

code Snippet

boolean checkArrayList(ArrayList arrayList){

for(int i=0;i<arrayList-1;i++){

if(arrayList[i]>arrayList[i+1])

return false;

}

return true;

}

This method will return true or false.

More info on binary Search Tree.

http://en.wikipedia.org/wiki/Binary_search_tree

More info on Code Snippets

http://www.geeksforgeeks.org/a-program-to-check-if-a-binary-tree-is-bst-or-not/

Visual Tutorial

http://www.youtube.com/watch?v=aNtDir94pcA

To search in binary tree

Following function help to search element in binary tree
Pre Requisite: Java ,Binary tree.
Level: medium
It is a simple method which will return the Search result in binary tree.
We have followed the recursive approach to solve this problem.
Binary tree is tree , where each node have at most 2 child.

As the parameter ,we will pass the Object which is the root of the binary tree.
“searchVariable” is the value which we have to search
METHOD:

public boolean searchInBinaryTree(Node N){

boolean result = false;
if(N == null)
return false;

if(N.value == searchVariable)
return true;

if(N.left != null)
result = searchInBinaryTree(N.left);

if(N.right != null)
result = searchInBinaryTree(N.right);

return result;
}
Note : link below will give you more information and help you in understanding in better way.