Sie sind auf Seite 1von 38

JP-II - Session 7

Module 8 Annotations Module 9 Reflection API

FPT APTECH COMPUTER EDUCATION HANOI

Session 6 - Review

JP-II - Session 7

MODULE 8 ANNOTATIONS

JP-II - Session 7

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

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 have a number of uses:


Information for the compiler Annotations can be used by the compiler to detect errors or suppress warnings. Compiler-time and deployment-time processing Software tools can process annotation information to generate code, XML files, and so forth. Runtime processing Some annotations are available to be examined at runtime.

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

Annotations Used by the Compiler


// Javadoc comment follows /** * @deprecated * explanation of why it was deprecated */ @Deprecated static void deprecatedMethod() { } } // mark method as a superclass method // that has been overridden @Override int overriddenMethod() { } // use a deprecated method and tell // compiler not to generate a warning @SuppressWarnings("deprecation") void useDeprecatedMethod() { objectOne.deprecatedMethod(); //deprecation warning suppressed }
JP-II - Session 7 11

@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

@SuppressWarnings Annotation Example


class Thu { @Deprecated public 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

@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

@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

Custom Annotation for Class

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

Custom Annotation for Method

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

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 Java programming language

JP-II - Session 7

22

Creating Custom Annotations

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 [1-2]

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

Custom Annotation Processor [2-2]

@SupportedAnnotationTypes annotation determines the type annotations that will be processed

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

Compiling Custom Annotation Processor

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

MODULE 9 - REFLECTION API

JP-II - Session 7

27

Module Obectives

JP-II - Session 7

28 28

Introduction to Reflection API

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 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. 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); } }

Example for Analyzing classes


JP-II - Session 7 31

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:

Example for Analyzing classes

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

Retrieving Field Values

To obtain the field value the three-step process to be followed are


Creating a Class object. Creating a Field object by invoking the getField() method in the Class object. Invoking one of the get() methods on the Field instance.

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

Assigning Field Values

To modify the value of a field, the steps to be followed are:


Creating a Class object Creating a Field object by invoking the getField() method on the Class object. Invoking one of the set() method on the Field instance.

The Field class provides several setter methods for modifying primitive types as well as objects.
JP-II - Session 7 35

Array and Reflection

The Array class


Is used to dynamically create and access arrays at runtime. Class.isArray() method is used to check whether a particular object is an array.

Arrays can be created during runtime by invoking the Array.newInstance() method.


The newInstance() method specifies a base type and length.

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

In this module, you learnt about:


Introduction to Reflection API Analyzing classes Working with objects Manipulating Arrays

JP-II - Session 7

38

Das könnte Ihnen auch gefallen