Java Tutorials - Herong's Tutorial Examples - v8.22, by Herong Yang
Use "interface" as Annotation
This section provides a tutorial example on how to use 'interface' type to do the same job, roughly, as 'annotation' type.
Based on the Java Language Specifications, an annotation type is actually an interface type.
So I think the Java compiler is actually:
Let's look at the following sample program that uses the annotation type:
/* HeaderAnnotation.java * Copyright (c) HerongYang.com. All Rights Reserved. */ class HeaderAnnotation { // Annotation declaration @interface Header { String usage(); // Usage of the targeted construct int version(); // Version number of targeted construct } // Annotation invocation @Header( usage="The execution entry point.", version=10 ) public static void main(String[] arg) { System.out.println("Hello world!"); } }
We can rewrite the above program using interface type:
/* HeaderInterface.java * Copyright (c) HerongYang.com. All Rights Reserved. */ class HeaderInterface { // Annotation declaration interface Header { public String usage(); // Usage of the targeted construct public int version(); // Version number of targeted construct } // Annotation invocation class Header1 implements Header { public String usage() { return "The execution entry point."; } public int version() { return 10; } } public static void main(String[] arg) { System.out.println("Hello world!"); } }
If you compile and run both programs, you will get:
herong> java HeaderAnnotation.java Hello world! herong> java HeaderInterface.java Hello world!
As you can see, we managed to do the same job, roughly, using interface type instead of annotation type.
Table of Contents
Execution Process, Entry Point, Input and Output
Primitive Data Types and Literals
Bits, Bytes, Bitwise and Shift Operations
Managing Bit Strings in Byte Arrays
Reference Data Types and Variables
StringBuffer - The String Buffer Class
System Properties and Runtime Object Methods
Generic Classes and Parameterized Types
Generic Methods and Type Inference
Lambda Expressions and Method References
Java Modules - Java Package Aggregation
Execution Threads and Multi-Threading Java Programs
ThreadGroup Class and "system" ThreadGroup Tree
Synchronization Technique and Synchronized Code Blocks
Deadlock Condition Example Programs
Garbage Collection and the gc() Method
Assert Statements and -ea" Option
►Annotation Statements and Declarations
►Use "interface" as Annotation
Default Values for Annotation Elements
Single-Element Annotation Invocation
No-Element (Marker) Annotation Invocation