×

Type Annotations in Java

Only declarations were eligible for annotations in earlier versions of Java. With Java 8, you may now annotate any type use, including types in declarations, generics, and casts:

@Encrypted String data;
List<@NonNull String> strings;
my_graph = (@Immutable Graph) tmpgraph;

Type annotations aren't the most attractive feature of the new Java release, at least not at first glance. Annotations are simply syntax, after all! Tools provide the semantics of annotations (i.e., their meaning and behavior). The new type annotation syntax and useful tools are introduced in this article to increase productivity and create software of higher quality.

Time to market is more crucial than ever in the financial sector because to the shifting regulatory and market conditions. However, giving up security or quality is not an option; even a simple misunderstanding of percentages and basis points might have negative effects. Every other industry is experiencing the same situation.

Annotations are undoubtedly already being used by Java programmers to raise the calibre of their code. In Java 1.5, the @Override annotation was first introduced. It might be challenging to keep track of which implementation of a method will be used at runtime in large projects with complex inheritance trees. Modifying a method declaration could, if done carelessly, prevent a subclass method from being invoked. By doing away with a method call in this way, a flaw or security hole may be created. Developers were able to describe methods as overriding a superclass method as a result of the introduction of the @Override annotation. If the application doesn't follow the developer's goals, the Java compiler will use the annotations to alert them.

Through methods like metaprogramming, annotations have also been crucial in increasing developer productivity. Annotations are supposed to be able to instruct tools on how to write new code, modify existing code, or act when the tool is running. For instance, utilising annotations on declarations like @Entity, the Java Persistence API (JPA), which was included in Java 1.5, enables developers to declaratively express the relationship between Java objects and database entities. These annotations enable run-time generation of SQL queries and mapping files by tools like Hibernate.

Annotations are used to support the DRY (Don't Repeat Yourself) principle in the context of JPA and Hibernate. Annotations are surprisingly easy to discover whenever you go for tools to assist development best practises! Examples include using Dependency Injection to lessen coupling and Aspect Oriented Programming to separate concerns.

Type Annotation SYNTAX:

This is the basic syntax,

@Encrypted String data;
List<@NonNull String> strings;
my_graph = (@Immutable Graph) tmpgraph;

It is as simple as defining an annotation with the ElementType to add a new type of annotation. Either the ElementType.TYPE USE target, the TYPE PARAMETER target, or both targets

@Target ({ElementType.TYPE_PARAMETER, ElementType.TYPE_USE})
public @interface Encrypted {      }

The target ElementType.TYPE PARAMETER indicates that the annotation can be added to a type variable's declaration, such as class MyClassT>.... Any use of a type may be the subject of an annotation, according to the ElementType.TYPE USE target (e.g., types appearing in declarations, generics, and casts).

Similar to annotations on declarations, once types are annotated in the source code, they can be both maintained in the class file and made accessible at run-time by reflection (using the RetentionPolicy.CLASS or RetentionPolicy.RUNTIME policy on the annotation definition). Type annotations differ from their predecessors primarily in two ways. First off, type annotations on the kinds of local variable declarations can also be stored in class files, unlike declaration annotations. Additionally, the complete generic type is kept and is available at runtime.

Annotations can be stored in the class file, but they have no impact on how the programme normally runs. A programmer might, for instance, specify two File variables and a Connection variable in the method's body:

File my_file = ………;
@Encrypted File encryptedFile = ………;
@Open Connection connection = …………;

If one of these files is passed to the connection's send(...) method during programme execution, the same method implementation will be called:

connection.send(my_file);
connection.send(encryptedFile);

Although the types of parameters can be annotated, methods cannot be overloaded depending on the annotated types, as would be expected given the lack of runtime effect:

public class Connection {
void send (@Encrypted File my_file) {  ……….  }
}

The reason behind this restriction is that the compiler has no way of determining the relationship between types that have various annotations or between types that are annotated and unannotated.

The connection variable is referred to as the method's "receiver" in the call connection.send(...). (The name "receiver" originates from the traditional analogy of passing messages between objects in object-oriented programming.) In order to allow type annotations to be added on a method's recipient, Java 8 changes the syntax for method declarations:

void send (@open Connection this, @Encrypted File my_file)

Once more, a method declared with the new receiver parameter syntax behaves the same as one declared with the conventional syntax because annotations have no effect on how the method is executed. In actuality, the sole purpose for which the new syntax is being used is to allow a type annotation to be written on the type of the receiver.

THE CHECKER FRAMEWORK:

A framework for checking Java annotations is the Checker Framework. Prof. Michael Ernst, co-lead of the JSR 308 specification, is the project's active open-source project manager. The framework was first released in 2007. A wide variety of annotations and checkers for identifying flaws including null-pointer dereferences, unit of measure inconsistencies, security vulnerabilities, and threading/concurrency issues are pre-packaged with the Checker Framework. The checks' outputs are reliable because they use type-checking internally; a tool utilising only heuristics might overlook potential errors, whereas a checker won't. During compilation, the framework performs these tests using the compiler API. You can also quickly build your own annotation checkers as a framework to find application-specific flaws.

The framework's objective is to find flaws without making you write a lot of annotations. Smart defaults and control-flow sensitivity are the two main aspects that enable it to achieve this. For instance, the checker believes that parameters are non-null by default for identifying null pointer issues. Conditionals can also be used by the checker to verify whether it is safe to dereference an expression.

void nullSafe (Object nonNullByDefault, @Nullable Object mightBeNull)
{
nonNullByDefault. hashCode (); //Due to default OK!
mightBeNull. hashCode ();
//This is a Warning!
if (mightBeNull != null)
{
mightBeNull. hashCode(); //Due to check OK!
}
}

In reality, you hardly ever need to insert annotations in the body of methods because the checker can infer and verify the annotations automatically thanks to defaults and control-flow sensitivity. The Java team has made sure that third party tool designers and users can make their own design decisions by keeping the semantics for annotations out of the official Java compiler. As a result, error checking can be tailored to a project's specific requirements.

You could say that having the option to define your own annotations also permits domain-specific type-checking. For instance, interest rates are frequently expressed in percentages in the banking industry, although the difference between rates is frequently expressed in basis points (1/100th of 1%). To make sure you don't confuse the two, you may define two annotations, @Percent and @BasisPoints, using the Units Checker of the Checker Framework:

BigDecimal perct = returnsPct (……);
// This statement annotates for returning @Percent
requiresBps(perct);
//Displays an error which is “@Basispoints is required”.

Because the Checker Framework is attentive to control-flow in this case, it determines that pct is a @Percent BigDecimal when the call to requiresBps(pct) is made based on two facts: A @Percent BigDecimal is tagged to be returned by returnsPct(...), and pct hasn't been reallocated before the call to requiresBps (...). To try to avoid these kinds of flaws, developers frequently utilise naming conventions. You are given a guarantee that these flaws won't exist even as the code develops and evolves thanks to the Checker Framework.

Millions of lines of code have already been run through the Checker Framework, finding hundreds of flaws in even thoroughly tested software. My favourite illustration was when the framework was used to analyse the well-known Google Collections library (now Google Guava), which uncovered null-pointer flaws that had escaped the notice of thorough testing and heuristic-based static analysis tools.

It is possible to achieve these outcomes without overcrowding the code. In reality, the Checker Framework only needs 2-3 annotations per 1000 lines of code to test a property!   


Related Topics

Java Integer remainder Unsigned() method

The remainderUnsigned() method of Java Integer class returns the unsigned remainder by dividing the first and second argument. Syntax public static int remainderUnsigned(int dividend, int divisor)  Parameters The ‘dividend’ and ‘divisor’ represents the value...

1 minute read.

Java Serialization

JAVA SERIALIZATION Serialization is a process by which objects can be represented as a sequence of bytes. These bytes have information about object's data, object's type and datatypes of members in...

3 minutes read.

Composition in Java

Composition Java uses the composition method to implement a has-a connection. Composition allows us to reuse code in the same way that Java inheritance does. The "is-a" relationship is implemented using the...

3 minutes read.

Vigesimal in Java

A number system with a base of 20 is known as the vigesimal in Java. A base-20 (base-score) numeric system, often known as a vigesimal system, is centered on the twenty...

4 minutes read.

Differences between Set and List in Java

Set in Java: The Java. util package contains an interface called the set. The set interface expands the Collection interface. A collection interface is an unordered collection of List where duplicates...

6 minutes read.

Java array list remove time complexity

Java: We know that java is one of the programming languages. The main feature of java which is not in C or object oriented programming language is platform independence. Not only the...

7 minutes read.

Java String isEmpty() method

Java String isEmpty() method checks whether current String is empty or not. Syntax: public boolean isEmpty() Returns It returns true, if length of String is 0 otherwise false. Java String isEmpty() method example 1    ...

1 minute read.

Crown Pattern in Java

We know the importance of solving pattern problems. We can solve pattern problems by using any programming language. There is no rule to translating into a particular programming language. We...

4 minutes read.

Java program to count the occurrences of each character

The count of each character is the frequency of the characters. For example, the given String is “Programming”. In the given string, the count of the characters ‘P’ -1, ’r’-2,...

6 minutes read.

What is String in Java?

What is String in Java? Strings are a collection of characters that are commonly used in Java programming. Strings are regarded as objects in the Java programming language. “String” is a Java...

4 minutes read.

URLConnection class in Java

A communication channel between the URL and the program is represented by the Java URLConnection class. It may be utilized to read from and write to the given resource the...

4 minutes read.

Hollow Diamond Pattern in Java

Why are patterns important? Programmers frequently create Java pattern programs to practice coding and ace interviews. Interviewers frequently test candidates' logical reasoning and implementation by asking about pattern programs. Hollow Diamond Pattern The...

7 minutes read.

Relatively Prime in Java

In this article, you will be very well equipped with a knowledge of a relatively prime number and also Java programs to determine whether a given integer is a relatively...

4 minutes read.

Intersection Point of two linked list in Java

In this article, you will be very well acknowledged about how to achieve the intersection point of two linked list in Java. There are several approaches to obtain. Surely each...

8 minutes read.

Java inheritance with Example

Java inheritance Java inheritance is a mechanism in which a child object acquires all the properties and behaviors of a parent object. It helps in reusing the code and establishes...

7 minutes read.

Implementing Queue Using Array in Java

We can implement queue by using array in Java. The queue is a linear data structure, and the array is one of the simplest data structures. Before implementing a queue...

4 minutes read.

India Map Pattern in Java

India Map Pattern is the pattern we'll code now using Java, as demonstrated. We will use a star in Java to print our India map.The specialty is that we will only...

4 minutes read.

Java Math atan2() Method

The atan2() method of Math class returns an angle theta from the conversion of rectangular coordinates to polar coordinates. Syntax: public static double atan2(double y, double x) Parameters: The parameter ‘y’ represents the ordinate...

3 minutes read.

Best Java Security Framework

The security of applications is currently our top concern when creating them. The applications or bits of code running over the network are exposed to dangers and may jeopardize integrity,...

3 minutes read.

Abstract Class Program in Java

Abstract Class Program in Java Abstraction is a technique by which a developer hides the implementation details from the user and shows only the functionality.It is not only confined to the...

6 minutes read.