26
83 Annotation Annotating Override Method Annotating Deprecated Method Annotation Annotation Annotate Annotation Target Annotation Retention Annotation Annotation Annotation Reflecting metadata metadata Java Javadoc metadata Javadoc null Javadoc non-null null null Tiger annotation metadata annotation package type declaration constructor method field parameter variable modifier name=value Java annotation Annotation Standard annotation types Tiger out of the box java.lang package annotation

Annotation - 碁峰資訊epaper.gotop.com.tw/pdf/A155.pdf · Retention meta-annotation Java annotation annotation class class Java virtual machine annotation class class annotation

  • Upload
    others

  • View
    141

  • Download
    0

Embed Size (px)

Citation preview

83

Annotation

Annotating Override

Method

Annotating Deprecated

Method

Annotation

Annotation Annotate

AnnotationTarget

AnnotationRetention

Annotation

Annotation

Annotation Reflecting

metadata metadata

Java

Javadoc metadata

Javadoc

null Javadoc

non-null null null

Tiger

annotation metadata

annotation package type declaration constructor

method field parameter variable modifier

name=value Java

annotation

Annotation Standard annotation types Tiger out of the box

java.lang package

annotation

Tiger annotation

Override

java.lang.Override method override

superclass method

Deprecated

java.lang.Deprecated method element

SupressWarnings

java.lang.SupressWarnings c lass method f ie ld

variable

Override annotation

@Overridepublic String toString( ) {

return super.toString( ) + " [modiÞed by subclass]";}

Deprecated

@Deprecated public class Betamax { ... }

SuppressWarnings

@SuppressWarnings("unchecked")public void nastyMethod( ) {

// }

annotation

annotation

annotation

<p.84>

annotation annotation

annotation annotation

anno ta t ion Override

84 Annotation

import

"java.lang" package

Deprecated SuppressWarnings annotation annotation

Java method class variable

annotation Override

annotation Override

anno ta t ion SuppressWarnings

unchecked annotation

annotation member

name=value annotation member

annotation annotation

Marker annotation

marker annotation member annotation

annotation member

annotation marker

marker

@MarkerAnnotation

Single-value annotation

single-value annotation member value single-value

annotation

@SingleValueAnnotation("some value")

Full annotation

full annotation annotation

annotation annotation

member

@Reviews({ // array@Review(grade=Review.Grade.EXCELLENT, reviewer="df"),@Review(grade=Review.Grade.UNSATISFACTORY, reviewer="eg",

comment="This method needs an @Override annotation")})

annotation

annotation

annotation

annotation

Annotation 85

...... XDoclet http://xdoclet.sourceforge.net

XDoclet

managing dependence EJB

metadata Javadoc

annotation XDoclet Javadoc

Javadoc tag

tag annotation

Java

@Overridde //

annotation XDoclet

Java

annotation XDoclet

Annotating Override MethodOverride annotat ion marker inter face

member method overr iding superclass

method override method

method list

Override marker interface

anno ta t ion a t @

Override overriding method

6-1

6-1. Override annotation

package com.oreilly.tiger.ch06;

public class OverrideTester {

86 Annotation

"at" @ annotation

public OverrideTester( ) { }

@Overridepublic String toString( ) {

return super.toString( ) + " [OverrideTester Implementation]";}

@Overridepublic int hashCode( ) {

return toString( ).hashCode( );}

}

hashCode() method

@Overridepublic int hasCode( ) {

return toString( ).hashCode( );}

hashCode() method overriding

annotation class

[javac] src\ch06\OverrideTester.java:1:method does not override a method from its superclass

[javac] @Override[javac] ^[javac] 1 error

annotation

.... . . overr idden method Override overr id ing

method overridden method

Java method overridden

method abstract

Annotating Deprecated MethodOverride java.lang.Deprecated marker annotation

Javadoc @deprecated tag

...

c l a s s me thod over r id ing

Deprecated

m ethod

Override-Tester

Annotating Deprecated Method 87

Deprecated marker interface member

Override

Override annotation 6-2 Deprecated

6-2. Deprecated annotation

package com.oreilly.tiger.ch06;

public class DeprecatedClass {

/*** method doSomethingElse( ) * doSomethingElse( ) */

@Deprecated public void doSomething( ) {// ...

}

public void doSomethingElse( ) {//

}}

annotation class

override method 6-3 class

6-3. overriding method

package com.oreilly.tiger.ch06;

public class DeprecatedTester extends DeprecatedClass {

public void doSomething( ) {// Override method

}}

class deprecation

[javac] src\ch06\DeprecatedTester.java:5: warning:[deprecation] doSomething( ) in

com.oreilly.tiger.ch06.DeprecatedClass has been deprecated[javac] public void doSomething( ) {[javac] ^

88 Annotation

"-Xlint:deprecation"

deprecation

XDoclet

.... . . @deprecated Javadoc

Deprecated annotation Javadoc comments

Javadoc class Deprecated

annotation

method class

@deprecated

javac -deprecation

-deprecation -Xlint:deprecation

-Xlint:deprecation JDK

Tiger

Tiger Tiger

collection Tiger typing

catch 22 Tiger

annotation SuppressWarnings

class method field/variable

SuppressWarnings Deprecated Override marker

interface value member value String array

String[] member array

annotation unchecked

Javadoc tag

annotation

"-Xlint"

Java

"switch"

enumerated

89

/*** Tiger method*/

@SuppressWarnings(value={"unchecked"})public void nonGenericsMethod( ) {

List wordList = new ArrayList( );

wordList.add("foo");}

Tige r

generic wordlist unchecked

SuppressWarnings annotation

annotation Tiger Tiger

annotation

[javac] src\ch06\SuppressWarningsTester.java:15:warning: [unchecked] unchecked call to add(E) as a member of the

raw type java.util.List[javac] wordList.add("foo");[javac] ^

Tiger

SuppressWarnings

/*** Tiger method*/

@SuppressWarnings(value={"unchecked", "fallthrough"})public void nonGenericsMethod( ) {

List wordList = new ArrayList( );

wordList.add("foo");}

member annotation

member member value

value=

/*** Tiger method*/

@SuppressWarnings({"unchecked", "fallthrough"})public void nonGenericsMethod( ) {

List wordList = new ArrayList( );

wordList.add("foo");}

90 Annotation

com.oreilly.tiger.ch06.Suppress-W arningsTester

m ember array

annotation value member

Annotation annotation

annotation

anno ta t ion T ige r

@interface

annotation Java interface

Java interface @interface

in ter face annota t ion

interface 6-4 marker interface

6-4. marker annotation

package com.oreilly.tiger.ch06;

/** * method class marker annotation*/

public @interface InProgress { }

method class

@com.oreilly.tiger.ch06.InProgresspublic void calculateInterest(ßoat amount, ßoat rate) {

// method }

member annotation 6-5

6-5. member annotation

package com.oreilly.tiger.ch06;

/*** annotation */

public @interface TODO {String value( );

}

"InProgress" package prefix

Javaclass

Annotation 91

member

member method value()

method member

annotation interface method

abstract

value

@TODO(stringValue)

@com.oreilly.tiger.ch06.InProgress@TODO("Figure out the amount of interest per month")public void calculateInterest(ßoat amount, ßoat rate) {

// method }

member 6-6

6-6. annotation member

package com.oreilly.tiger.ch06;

public @interface GroupTODO {

public enum Severity { CRITICAL, IMPORTANT, TRIVIAL, DOCUMENTATION };

Severity severity( );String item( );String assignedTo( );

}

enumerated severity member item

assignedTo TODO

@com.oreilly.tiger.ch06.InProgress@GroupTODO(

severity=GroupTODO.Severity.CRITICAL,item="Figure out the amount of interest per month",assignedTo="Brett McLaughlin"

)public void calculateInterest(ßoat amount, ßoat rate) {

// method }

member

6-7 6-6

92 Annotation

Java

JavaBean fried-

and-true

setXXX() getXXX() m ethod

6-5 "TODO"

enumerated

6-7. annotation

package com.oreilly.tiger.ch06;

import java.util.Date;

public @interface GroupTODO {

public enum Severity { CRITICAL, IMPORTANT, TRIVIAL, DOCUMENTATION };

Severity severity( ) default Severity.IMPORTANT;String item( );String assignedTo( );String dateAssigned( );

}

generic

......extending interface annotation @interface

java.lang.annotation.Annotation

extend annotation

ex tend anno ta t ion

annotation

Annotation Annotateannotate annotate annotation

Javadoc comments class

me ta -anno ta t ion anno ta t ion

annotation annotation

meta-annotation java.lang.annotation

package

Target

meta-annotation annotation

Annotation Annotate 93

Retention

meta-annotation annotation

class annotation

Java virtual machine class annotation

Documented

meta-annotation annotation

API

Inherited

meta-annotation class annotation

annotated

meta-

annotation

Annotation Targetmeta -anno ta t ion Target

annotation annotation

annotation

Target annotation

@Target({ElementType.TYPE,ElementType.METHOD,ElementType.CONSTRUCTOR,ElementType.ANNOTATION_TYPE})

public @interface TODO {

Target member array

java.lang.annotation.ElementType enum enumerated

enum annotation

6-8

6-8. ElementType enum

package java.lang.annotation;

public enum ElementType {TYPE, // Class, interface, or enum ( annotation)

94 Annotation

Target

ElementType[]

FIELD, // Field ( enumerated values)METHOD, // Method ( constructors)PARAMETER, // Method parameterCONSTRUCTOR, // ConstructorLOCAL_VARIABLE, // Local variable catch ANNOTATION_TYPE, // Annotation Types (meta-annotations)PACKAGE // Java Package

}

import Target ElementType 6-9

TODO annotation 6-5

6-9. annotation annotate

package com.oreilly.tiger.ch06;

import java.lang.annotation.ElementType;import java.lang.annotation.Target;

/*** annotation */

@Target({ElementType.TYPE,ElementType.METHOD,ElementType.CONSTRUCTOR,ElementType.ANNOTATION_TYPE})

public @interface TODO {String value( );

}

Target meta-annotation 6-

10 meta-annotation

6-10. Target annotation

package java.lang.annotation;

@Documented@Retention(RetentionPolicy.RUNTIME);@Target(ElementType.ANNOTATION_TYPE)public @interface Target {

ElementType[] value( );}

.... . . annotation

Target

Target

ElementTypes

Annotation Target 95

Annotation RetentionRetention meta -anno ta t ion Java

annotation annotation class

class Java virtual machine annotation

class class annotation

Retention

Target annotation public @interface

annotation retention Target Retention

enum c la s s

java.lang.annotation.RetentionPolicy enum 6-11

6-11. RetentionPolicy enum

package java.lang.annotation;

public enum RetentionPolicy {SOURCE, // Annotation CLASS, // Annotation class , VM RUNTIME // Annotation class VM

}

anno ta t ion re ten t ion po l i cy

RetentionPolicy.CLASS annotation VM class

Retention SuppressWarnings annotation

annotation

class bytecode

@Retention(RetentionPolicy.SOURCE)public @interface SuppressWarnings {

Annotation annotation

Annotation

annotation InProgress TODO GroupTODO

J avadoc

96 Annotation

import java.lang.annotation.Retention java.lang.annotation.RetentionPolicy

Ant buildfile"ant Javadoc"

Javadoc

Documented meta-annotation

annotation Javadoc

Javadoc

Documented API

com.oreilly.tiger.ch06 package AnnotationTester

class calculateInterest() method

6-1

method

@com.oreilly.tiger.ch06.InProgress@GroupTODO(

severity=GroupTODO.Severity.CRITICAL,item="Figure out the amount of interest per month",assignedTo="Brett McLaughlin",dateAssigned="04-26-2004"

)public void calculateInterest(ßoat amount, ßoat rate) {

// method }

Annotation 97

InProgress GroupTODO annotation

Javadoc

@Documented meta-annotation

Javadoc annotat ion InProgress

GroupTODO TODO 6-12

InProgress annotation

6-12. InProgress

package com.oreilly.tiger.ch06;

import java.lang.annotation.Documented;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;

/*** method class marker annotation*/

@Documented@Retention(RetentionPolicy.RUNTIME)public @interface InProgress { }

Retention meta-annotation class

Documented anno ta t ion

RetentionPolicy.RUNTIME re ten t ion

com.oreilly.tiger.ch03 annotation

Javadoc class Javadoc

com.oreilly.tiger.ch06 AnnotationTester

calculateInterest() method 6-2 method

annotation Javadoc

Annotation c la s s

deprecated

class extend

deprecated superclass

deprecated class deprecation

subclass

98 Annotation

"ant clean"

class Javadoc

Javadoc

deprecated c lass

deprecated class superclass Inherited

meta-annotation

annotat ion

InProgress 6-13 annotation class

6-13. InProgress annotation

package com.oreilly.tiger.ch06;

import java.io.IOException;import java.io.PrintStream;

@InProgresspublic class Super {

public void print(PrintStream out) throws IOException {out.println("Super printing...");

}}

6-14 extend Super class

Annotation 99

6-14. Super extending

package com.oreilly.tiger.ch06;

import java.io.IOException;import java.io.PrintStream;

public class Sub extends Super {

public void print(PrintStream out) throws IOException {out.println("Sub printing...");

}}

class Javadoc 6-3 Super

Sub class

6-4

InProgress annotation

InProgress

100 Annotation

@Documented@Inherited@Retention(RetentionPolicy.RUNTIME)public @interface InProgress { }

class Javadoc

Sub

reflection

reflection Sub Javadoc

re f l ec t ion anno ta t ion Annota t ion

Reflecting

......interface Inherited annotation subclass

annotation method annotation

superclass overr ide method

method annotation superclass annotation

subclass

Annotation 101

TIP

Annotation Reflectingannotation

Javadoc

re f lec t ion c lass f ie ld method

annotation java.lang.reflect package

anno ta t ion isAnnotationPresent()

method annotation true/false

public void testAnnotationPresent(PrintStream out) throws IOException {Class c = Super.class;boolean inProgress = c.isAnnotationPresent(InProgress.class);if (inProgress) {

out.println("Super is In Progress");} else {

out.println("Super is not In Progress");}

}

run-ch06:[echo] Running Chapter 6 examples from Java Tiger:

A Developer's Notebook[echo] Running ReßectionTester...[java] Super is In Progress

Inherited annotation

Annotation

public void testInheritedAnnotation(PrintStream out) throws IOException {Class c = Sub.class;boolean inProgress = c.isAnnotationPresent(InProgress.class);if (inProgress) {

out.println("Sub is In Progress");

102 Annotation

ReflectionTesterclass

Annotation

"Super"

} else {out.println("Sub is not In Progress");

}}

Sub Super

InProgress annotation Inherited

subclass method

run-ch06:[echo] Running Chapter 6 examples from Java Tiger: A Developer's Notebook[echo] Running VarargsTester...[java] Super is In Progress[java] Sub is In Progress

Javadoc reflection

marker in te r f ace

isAnnotationPresent() annotation

public void testGetAnnotation(PrintStream out)throws IOException, NoSuchMethodException {

Class c = AnnotationTester.class;MethodElement element = c.getMethod("calculateInterest",

ßoat.class, ßoat.class);

GroupTODO groupTodo = element.getAnnotation(GroupTODO.class);String assignedTo = groupTodo.assignedTo( );

out.println("TODO Item on Annotation Tester is assigned to: '" +assignedTo + "'");

}

method Annota t ionTes te r

calculateInterest() method annotation

GroupTODO annotation assignedTo

method

run-ch06:[echo] Running Chapter 6 examples from Java Tiger:

A Developer's Notebook

[echo] Running ReßectionTester...[java] Super is In Progress[java] Sub is In Progress[java] TODO Item on Annotation Tester is assigned to:

'Brett McLaughlin'

annotationreflection

annotation

Annotation Reflecting 103

getAnnotation()

annotation iterate

annotation getAnnotations()

method annotation

public void printAnnotations(AnnotatedElement e, PrintStream out)throws IOException {

out.printf("Printing annotations for '%s'%n%n", e.toString( ));

Annotation[] annotations = e.getAnnotations( );for (Annotation a : annotations) {

out.printf(" * Annotation '%s' found%n",a.annotationType( ).getName( ));

}}

AnnotationTester calculateInterest() method

run-ch06:[echo] Running Chapter 6 examples from Java Tiger: A Developer's Notebook[echo] Running ReßectionTester...[java] Super is In Progress[java] Sub is In Progress[java] TODO Item on Annotation Tester is assigned to: 'Brett McLaughlin'[java] Printing annotations for 'public void com.oreilly.tiger.ch06.Annotat

ionTester.calculateInterest(�oat,�oat)'

[java] * Annotation 'com.oreilly.tiger.ch06.InProgress' found[java] * Annotation 'com.oreilly.tiger.ch06.GroupTODO' found

6-15

ReflectionTester reflection annotation

method

6-15. ref lection annotation method

package com.oreilly.tiger.ch06;

import java.io.IOException;import java.io.PrintStream;import java.lang.reßect.AnnotatedElement;import java.lang.annotation.Annotation;

public class ReßectionTester {

104 Annotation

for/in

printf()

m ethod

annotation

getDeclared-Annotations()

getAnnotations()

public ReßectionTester( ) {}

public void testAnnotationPresent(PrintStream out) throws IOException {Class c = Super.class;boolean inProgress = c.isAnnotationPresent(InProgress.class);if (inProgress) {

out.println("Super is In Progress");} else {

out.println("Super is not In Progress");}

}

public void testInheritedAnnotation(PrintStream out) throws IOException {Class c = Sub.class;boolean inProgress = c.isAnnotationPresent(InProgress.class);if (inProgress) {

out.println("Sub is In Progress");} else {

out.println("Sub is not In Progress");}

}

public void testGetAnnotation(PrintStream out)throws IOException, NoSuchMethodException {

Class c = AnnotationTester.class;AnnotatedElement element = c.getMethod("calculateInterest",

ßoat.class, ßoat.class);

GroupTODO groupTodo = element.getAnnotation(GroupTODO.class);String assignedTo = groupTodo.assignedTo( );

out.println("TODO Item on Annotation Tester is assigned to: '" +assignedTo + "'");

}

public void printAnnotations(AnnotatedElement e, PrintStream out)throws IOException {

out.printf("Printing annotations for '%s'%n%n", e.toString( ));

Annotation[] annotations = e.getAnnotations( );for (Annotation a : annotations) {

out.printf(" * Annotation '%s' found%n",a.annotationType( ).getName( ));

}}

AnnotatedElementreflection

m ethod class

interface

annotationm ethod

Annotation Reflecting 105

6-15. ref lection annotation method

public static void main(String[] args) {try {

ReßectionTester tester = new ReßectionTester( );

tester.testAnnotationPresent(System.out);tester.testInheritedAnnotation(System.out);

tester.testGetAnnotation(System.out);

Class c = AnnotationTester.class;AnnotatedElement element = c.getMethod("calculateInterest",

ßoat.class, ßoat.class);tester.printAnnotations(element, System.out);

} catch (Exception e) {e.printStackTrace( );

}}

}

java.lang.reßect.AnnotatedElement interface Tiger

reflection interface Class Constructor

Field Method Package AccessibleObject

annotation AnnotatedType

method

public Annotation getAnnotation(Class annotationType);

public Annotation[] getAnnotations( );

public Annotation[] getDeclaredAnnotations( );

public boolean isAnnotationPresent(Class annotationType);

Java AnnotatedType

method annotation

.... . . annota t ion

annotation RetentionpPolicy.RUNTIME

annotation VM

106 Annotation

generic

Javadoc Annotated-Element

m ethod

reflection annotation

Inherited Documented annotation annotation

@Retention(RetentionPolicy.RUNTIME)

/

Annotation Reflecting 107

108 Annotation