Java Tutorial/Trail: Annotations

From Wikiversity
Jump to navigation Jump to search

Annotations[edit | edit source]

Annotations allow to provide further information to classes that can be discarded by the compiler during compilation (RetentionPolicy.SOURCE), retained in the class file but not in the Java virtual machine (RetentionPolicy.CLASS) or retained during execution (RetentionPolicy.RUNTIME).

For C and C++ programmers the following example will illustrate the effect:

 // This defines an annotation called "Typedef".
 @interface Typedef {
	String type () default "default type";
 }

 // The Typedef annotation is applied to an integer variable called "filedescriptor".
 public class AnnotationTest
 {
	@Typedef(type="fd_t") int filedescriptor;

	@Typedef(type="fd_t") int getFiledescriptor () { return filedescriptor; }
 }

The example shows how additional type information can be given for a primitive type. A similar effect would be possible with the reserved word typedef in C and C++. Unlike the C implementation the Java compiler would not comment on the assignment of incompatible types, however. A special processing phase would be required to verify this (in Java) uncommon type information. This verification could be added by the compiler or even by a ClassLoader.

The convenience of using just fd_t as the type name is not available in Java because Java does not have a preprocessor like C does; it is possible to preprocess Java code with the C preprocessor cpp, though. Otherwise the full name of the new type is always @Typedef(type="fd_t") int, because the annotation must be used wherever the additional information is required.

See also[edit | edit source]

External links[edit | edit source]