Session7 Module8-9 Annotations Reflection
Session7 Module8-9 Annotations Reflection
Session 6 - Review
JP-II - Session 7
MODULE 8 ANNOTATIONS
JP-II - Session 7
Module Objectives
Categories of Annotation
Creating Custom Annotations
JP-II - Session 7
What is Annotation?
Annotations can be defined as metadata which provide additional information about existing pieces of data. Annotations help associate metadata to the program elements. They affect the way a program is treated by tools and libraries which in turn can affect program semantics. Annotations can be read from source files or class files. Comments in code are replaced by annotations in many places. Annotations helps the programmer to avoid writing of reusable code by enabling tools to generate such reusable code from annotations present in the source code.
JP-II - Session 7 5
Java Annotations
An annotation is a meta-tag used by the programmer in the code. Annotation represents the specific use of the type. Annotation type helps to define an annotation. This is used by the programmer when a custom annotation is created. The example below defines a Annotation and use it in consuming code:
// Definition of an Annotation type public @interface TestAnnotation { String value; } // Usage of Annotation @TestAnnotation (value="name") public void display() {}
JP-II - Session 7 6
Uses of Annotations
Annotations can be applied to a program's declarations of classes, fields, methods, and other program elements.
JP-II - Session 7 7
DO and DONT
DO DONT
If you want your if the metadata application to be changes the portable between design of the class. application servers if the metadata and databases changes the When you want to design of code configure on a per dealing with class. deployment basis .
JP-II - Session 7 8
Categories of Annotations
Marker Annotations
Consists of name and have no values associated Has no additional present, such as @TestAnno
Single-value Annotations
Consists of single value, similar to marker ones. Can be represented: data= value pair Example: @TestAnno(Testing)
Full Annotations
Consists of multiple data members. Each member represented by data= value pair @TestAnno(owner=Stephen, value=class scope)
JP-II - Session 7 9
Built-in Annotations
@Deprecated
@Override
@SupressWarnings @Target @Retention @Inherited
JP-II - Session 7
10
@Deprecated annotation
When you design an API, carefully consider whether it supersedes an old API. If it does, and you wish to encourage developers (users of the API) to migrate to the new API, then deprecate the old API. Valid reasons to deprecate an API include:
It is insecure, buggy, or highly inefficient It is going away in a future release It encourages bad coding practices
JP-II - Session 7
12
@SuppressWarnings Annotation
To inform the compiler to suppress certain warnings in the annotated code element that would otherwise have been generate.
JP-II - Session 7
13 13
@SuppressWarnings Annotation
This annotation indicates that compiler warnings should be shielded in the annotated element and all of its sub-elements. The set of warnings suppressed in an element is the superset of the warnings in all of its containing subelements. As an example, if you annotate a class to suppress one warning and one of its methods to suppress another warning, both warnings will be suppressed at the method level only.
JP-II - Session 7 14
@Documented Annotation
@Retention Annotation
The annotation type annotated with @Retention determines where and how long the annotation is retained. It can have 3 values:
RetentionPolicy.SOURCE RetentionPolicy.CLASS RetentionPolicy.RUNTIME
JP-II - Session 7
17
EXAMPLE
@Retention(RetentionPolicy.SOURCE) @interface Test_Retention{ String v1(); } class RetentionTest{ @Test_Retention(v1="Hello") public void thu(){ System.out.println("Test annotations"); } } class RetentionAnno{ public static void main(String args[]){ new RetentionTest().thu(); } }
JP-II - Session 7 18
Custom Annotation
Annotations can be added at class level, field level, and method level.
Java 5 allowed annotation processing during compilation of code as well as during execution.
Java SE 6 introduced an enhanced feature in annotations, called the Pluggable Annotation Processing API. This API helps application developers to write Customized Annotation Processor which can be plugged-in to the code dynamically.
JP-II - Session 7
To create an annotation type for classes, the "@" symbol followed by the keyword, interface and the annotation name is used. Parameters can be added to the Annotation Declaration.
Parameter will not have null value Parameter can have default value Parameter are written as simple methods
JP-II - Session 7
20
While creating an Annotation for a methods, the annotation starts with @. The order of assigning values to the members of the annotations is of no importance. The decleration of annotation type should be in the same package as the class using the Annotation
JP-II - Session 7 21
javax.lang.model package - APIs in this package are used for modeling the Java programming language
JP-II - Session 7
22
Custom annotations can be created both at class level and method level with properties and default values.
ClassLevelAnnotation.java
Can be defined using @Target annotation with value as ElementType.TYPE ElementType defines various program elements such as class, interface, or enum that an annotation type can target.
MethodLevelAnnotation.java
Can be defined using @Target annotation with value ElementType.METHOD
JP-II - Session 7
23
Custom annotation processor class should extend from the AbstractProcessor class It must override the process() method provided by the AbstractProcessor class Custom annotation processor class must use two class-level annotations namely, @SupportedAnnotationTypes and @SupportedSourceVersion
JP-II - Session 7
24
of
* indicates that all types of annotations will be processed @SupportedSourceVersion annotation determines which version of source code will be supported by annotation processor
JP-II - Session 7
25
The processor can be invoked either through the javac command-line utility or programmatically through a standalone Java class javac command-line utility of Java SE 6 provides an option named -processor that accepts the fully qualified name of custom annotation processor along with other Java source files having custom annotations
JP-II - Session 7
26
JP-II - Session 7
27
Module Obectives
JP-II - Session 7
28 28
Reflection is the ability of classes, objects and interfaces to find information about itself. The reflection API are used to write development tools, such as debuggers, class browsers and GUI builder Reflection API is used for the following purposes:
Analyzing classes Controlling objects Controlling with arrays
JP-II - Session 7
29 29
Analyzing classes
Retrieving fields:
By invoking getField() method on a class object.
Method information:
By invoking getMethods() method on a class object. 30 JP-II - Session 7 30
import java.lang.reflect.*; public class Test { public int m,n; public Test() {}; public Test(int m, int n) {this.m = 1 m; this.n=n;} public void xem() {System.out.println("m, n = " + m+ ", " + n);} public void nhap(int u, int v) {m=u;n=v;} } public class Main{ public static void main(String[] args){ Test t = new Test(); printClassName(t); printFieldNames(t); printMethodNames(t); printConstructors(t); } static void printClassName(Thu t){ Class c = t.getClass(); System.out.println("\nRetrieved Class Name: " + c.getName()); }
static void printFieldNames(Test t) { String className, fieldName, fieldType; 2 Class c = t.getClass(); className = c.getName(); Field [] f = c.getFields(); System.out.println("\n"); for (int i = 0; i < f.length; i++) { fieldName = f[i].getName(); Class ft = f[i].getType(); fieldType = ft.getName(); System.out.println("Field Name: " + fieldName + ", Field Type: " + fieldType); } }
static void printMethodNames(Test t) { String className, methodName; String methodType, methodParaName; Class c = t.getClass(); Method[] m = c.getMethods(); for (int i = 0; i < m.length; i++){ methodName = m[i].getName(); System.out.println("\nMethod 3 Name: " + methodName); methodType = m[i].getReturnType().getName(); System.out.println("Return Type: " + methodType); Class[] p = m[i].getParameterTypes(); System.out.print("Parameter Types:"); for (int k = 0; k < p.length; k++) { methodParaName = p[k].getName(); System.out.print(" " + methodParaName); } } }
static void printConstructors(Test t) { String className, fieldName, fieldType; Class c = t.getClass(); 4 Constructor [] cons = c.getConstructors(); System.out.println("\n"); for (int i = 0; i < cons.length; i++) { System.out.println("Constructor name: " + cons[i].toString()); } } } //end main
Part of results:
JP-II - Session 7
32 32
Create object
The newInstance() method is invoked on a class instance to create an object with the no-argument constructor. The newInstance() method is invoked on a Constructor object to create an object with a parameterize constructor. Steps are:
Create a class instance. Invoke getConstructor() method. Invoke newInstance() method.
JP-II - Session 7
33 33
The Field class contains getter methods that return primitive values as well as objects.
For example: getInt() method returns int.
JP-II - Session 7
34
The Field class provides several setter methods for modifying primitive types as well as objects.
JP-II - Session 7 35
JP-II - Session 7
36
Example
package reflectiondemo; import java.lang.reflect.Array; public class ReflectDemo1 { public static void main(String[] args) { int[] intArray = {12, 78}; displayArray(intArray); } static void displayArray(Object source){ System.out.println(Array.get(source, 0)); Array.set(source, 0, 100); System.out.println(Array.get(source, 0)); } }
JP-II - Session 7
37
Module 9: Summary
JP-II - Session 7
38