Session7 Module8-9 Annotations Reflection
-
Upload
anh-van-nguyen -
Category
Documents
-
view
225 -
download
0
Transcript of Session7 Module8-9 Annotations Reflection
-
8/2/2019 Session7 Module8-9 Annotations Reflection
1/38
FPT APTECH COMPUTER EDUCATION HANOI
JP-II - Session 7
Module 8 Annotations
Module 9 Reflection API
-
8/2/2019 Session7 Module8-9 Annotations Reflection
2/38
Session 6 - Review
JP-II - Session 7 2
-
8/2/2019 Session7 Module8-9 Annotations Reflection
3/38
MODULE 8 ANNOTATIONS
JP-II - Session 7 3
-
8/2/2019 Session7 Module8-9 Annotations Reflection
4/38
Module Objectives
Explain the concept of Annotation
Describe features of Annotation
The uses of Annotation
Categories of Annotation
Creating Custom Annotations
JP-II - Session 7 4
-
8/2/2019 Session7 Module8-9 Annotations Reflection
5/38
What is Annotation?
Annotations can be defined as metadata whichprovide additional information about existingpieces of data.
Annotations help associate metadata to the programelements. They affect the way a program is treated by
tools and libraries which in turn can affect programsemantics. Annotations can be read from source files or class
files. Comments in code are replaced by annotationsin many places.
Annotations helps the programmer to avoid writing ofreusable code by enabling tools to generate suchreusable code from annotations present in the sourcecode.
JP-II - Session 7 5
-
8/2/2019 Session7 Module8-9 Annotations Reflection
6/38
Java Annotations
An annotation is a meta-tag used by the programmer inthe code. Annotation represents the specific use of thetype.
Annotation type helps to define an annotation. This isused by the programmer when a custom annotation iscreated.
The example below defines a Annotation and use it inconsuming 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
-
8/2/2019 Session7 Module8-9 Annotations Reflection
7/38
Uses of Annotations
Annotations have a number of uses: Information for the compiler Annotations can be
used by the compiler to detect errors or suppresswarnings.
Compiler-time and deployment-time processing
Software tools can process annotation information togenerate code, XML files, and so forth.
Runtime processing Some annotations areavailable to be examined at runtime.
Annotations can be applied to a program'sdeclarations of classes, fields, methods,and other program elements.
JP-II - Session 7 7
-
8/2/2019 Session7 Module8-9 Annotations Reflection
8/38
DO and DONT
DO
if the metadatachanges the
design of the class. if the metadata
changes the
design of codedealing with class.
DONT
If you want yourapplication to be
portable betweenapplication serversand databases
When you want toconfigure on a perdeployment basis .
JP-II - Session 7 8
-
8/2/2019 Session7 Module8-9 Annotations Reflection
9/38
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=classscope)
JP-II - Session 7 9
-
8/2/2019 Session7 Module8-9 Annotations Reflection
10/38
Built-in Annotations
@Deprecated
@Override
@SupressWarnings
@Target
@Retention
@Inherited
JP-II - Session 7 10
-
8/2/2019 Session7 Module8-9 Annotations Reflection
11/38
//use a deprecated method and tell//compiler not to generate a warning
@SuppressWarnings("deprecation")void useDeprecatedMethod() { objectOne.deprecatedMethod();
//deprecation warning suppressed
}
Annotations Used by the Compiler
// Javadoc comment follows
/*** @deprecated
* explanation of why it was deprecated
*/
@Deprecatedstatic void deprecatedMethod() { }}
//mark method as a superclass method//that has been overridden@Override int overriddenMethod() { }
JP-II - Session 7 11
-
8/2/2019 Session7 Module8-9 Annotations Reflection
12/38
@Deprecated annotation
When you design an API, carefully considerwhether it supersedes an old API.
If it does, and you wish to encouragedevelopers (users of the API) to migrate to the
new API, then deprecate the old API. Validreasons 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
-
8/2/2019 Session7 Module8-9 Annotations Reflection
13/38
@SuppressWarnings Annotation
To inform thecompiler to suppresscertain warnings inthe annotated code
element that wouldotherwise have beengenerate.
13JP-II - Session 7 13
-
8/2/2019 Session7 Module8-9 Annotations Reflection
14/38
@SuppressWarnings Annotation
This annotation indicates that compiler warningsshould 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 sub-
elements.
As an example, if you annotate a class to suppress
one warning and one of its methods to suppressanother warning, both warnings will be suppressed
at the method level only.
JP-II - Session 7 14
-
8/2/2019 Session7 Module8-9 Annotations Reflection
15/38
@SuppressWarnings AnnotationExample
class Thu {
@Deprecatedpublic void chao(){
System.out.println("\n Hello");}
}class ThuTest{
@SuppressWarnings({"deprecation"})public void test(){
Thu t = new Thu();t.chao();
}}
public class SuppressWarning{public static void main(String[] args){
ThuTest h = new ThuTest();h.test();
}}
JP-II - Session 7 15
-
8/2/2019 Session7 Module8-9 Annotations Reflection
16/38
@Documented Annotation
The @Documented annotation specifies that it
should be included in the documentation,
documented by the javadoc tool.
The use of the @Documented annotation in the
code will enable tools like javadoc to process it
and include the annotation type information in
the generated document.
JP-II - Session 7 16
-
8/2/2019 Session7 Module8-9 Annotations Reflection
17/38
@Retention Annotation
The annotation type annotated with @Retentiondetermines where and how long the annotationis retained.
It can have 3 values:
RetentionPolicy.SOURCE
RetentionPolicy.CLASS
RetentionPolicy.RUNTIME
JP-II - Session 7 17
-
8/2/2019 Session7 Module8-9 Annotations Reflection
18/38
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
-
8/2/2019 Session7 Module8-9 Annotations Reflection
19/38
Custom Annotation
Annotations can be added at class level, fieldlevel, and method level.
Java 5 allowed annotation processing duringcompilation of code as well as during execution.
Java SE 6 introduced an enhanced feature inannotations, called the Pluggable AnnotationProcessing API.
This API helps application developers to writeCustomized Annotation Processor which can beplugged-in to the code dynamically.
JP-II - Session 7
-
8/2/2019 Session7 Module8-9 Annotations Reflection
20/38
Custom Annotation for Class
To create an annotation type for classes, the"@" symbol followed by the keyword, interfaceand 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
-
8/2/2019 Session7 Module8-9 Annotations Reflection
21/38
Custom Annotation for Method
While creating an Annotation for amethods, the annotation starts with @.
The order of assigning values to the
members of the annotations is of noimportance.
The decleration of annotation type should
be in the same package as the class usingthe Annotation
JP-II - Session 7 21
-
8/2/2019 Session7 Module8-9 Annotations Reflection
22/38
Pluggable Annotation Processing
Consists of two parts. They are: javax.annotation.processing package -
APIs in this package are used to declare
annotation processors and interact with them javax.lang.model package - APIs in this
package are used for modeling the Javaprogramming language
JP-II - Session 7 22
-
8/2/2019 Session7 Module8-9 Annotations Reflection
23/38
Creating Custom Annotations
Custom annotations can be created both atclass level and method level with properties anddefault values.
ClassLevelAnnotation.java
Can be defined using @Target annotation with value asElementType.TYPE
ElementType defines various program elements such asclass, interface, or enum that an annotation type can target.
MethodLevelAnnotation.java
Can be defined using @Target annotation with valueElementType.METHOD
JP-II - Session 7 23
-
8/2/2019 Session7 Module8-9 Annotations Reflection
24/38
24
Custom Annotation Processor [1-2]
Custom annotation processor class shouldextend from the AbstractProcessor class
It must override the process() method providedby the AbstractProcessor class
Custom annotation processor class must usetwo class-level annotations namely,@SupportedAnnotationTypes and
@SupportedSourceVersion
JP-II - Session 7
-
8/2/2019 Session7 Module8-9 Annotations Reflection
25/38
Custom Annotation Processor [2-2]
@SupportedAnnotationTypesannotation determines the type ofannotations that will be processed
* indicates that all types of annotations willbe processed
@SupportedSourceVersion annotation
determines which version of source codewill be supported by annotation processor
JP-II - Session 7 25
-
8/2/2019 Session7 Module8-9 Annotations Reflection
26/38
26
Compiling Custom Annotation Processor
The processor can be invoked eitherthrough the javac command-line utility orprogrammatically through a standalone
Java class javac command-line utility of Java SE 6
provides an option named -processor thataccepts the fully qualified name of customannotation processor along with otherJava source files having customannotations
JP-II - Session 7
-
8/2/2019 Session7 Module8-9 Annotations Reflection
27/38
MODULE 9 - REFLECTION API
JP-II - Session 7 27
-
8/2/2019 Session7 Module8-9 Annotations Reflection
28/38
Module Obectives
28JP-II - Session 7 28
-
8/2/2019 Session7 Module8-9 Annotations Reflection
29/38
Introduction to Reflection API
Reflection is the ability of classes, objects andinterfaces to find information about itself.
The reflection API are used to write developmenttools, such as debuggers, class browsers andGUI builder
Reflection API is used for the followingpurposes:
Analyzing classes Controlling objects
Controlling with arrays
29JP-II - Session 7 29
-
8/2/2019 Session7 Module8-9 Annotations Reflection
30/38
Analyzing classes
Retrieving class name: If an instance of the class is available, then by
invoking getName() method, the class name can be
retrieved.
Retrieving fields: By invoking getField() method on a class object.
Retrieving class constructors:
By invoking getConstructors() method on a
class object.
Method information:
By invoking getMethods() method on a class
object. 30JP-II - Session 7 30
import java.lang.reflect.*; static void printFieldNames(Test t)
-
8/2/2019 Session7 Module8-9 Annotations Reflection
31/38
Example forAnalyzing classes
import java.lang.reflect. ;public class Test {
public int m,n;public Test() {};public Test(int m, int n) {this.m =
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;
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("FieldName: " + fieldName + ", Field Type: " +fieldType);
}}
12
JP-II - Session 7 31
static void printMethodNames(Test t) { static void printConstructors(Test t)
-
8/2/2019 Session7 Module8-9 Annotations Reflection
32/38
32
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("\nMethodName: " + 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);}
}}
{String className, fieldName,
fieldType;Class c = t.getClass();Constructor [] cons =
c.getConstructors();
System.out.println("\n");for (int i = 0; i