首页 > 代码库 > Java学习笔记十(注解)

Java学习笔记十(注解)

 

 1.介绍

注解是JavaSE5.0開始提供的一项新特性,利用此特性能够通过特定的注解标签为程序提供一些描写叙述性信息。

这些描写叙述性信息能够在编译或执行时为编译器、执行环境提供附加的信息。从而简化开发。


 2.自己定义注解

1.声明自己的注解

@interface <注解名称>{<注解属性类型> <注解属性名称>[default<默认值>]}

<span style="font-family:SimSun;font-size:18px;">@interface myTest{
	//自己定义注解属性
	String msg();
	
}</span>

2.确定注解使用目标

目的不同,注解能够有不同的使用目标。

比如对方法注解,对构造器注解,对变量字段注解,对类或者接口注解等等

@Target(ElementType.<使用目标点>)

<span style="font-family:SimSun;font-size:18px;">//声明此注解仅仅能对类或者接口进行注解
@Target(ElementType.TYPE)
@interface myTest{
	//自己定义注解属性
	String msg();
	
}</span>


3.确定注解的使用时效

依据使用目的不同,注解能够有不同的使用时效。

Class:注解存在于雷文件里。但在执行时虚拟机不能够获取注解信心

SOURCE:注解仅仅存在于源码中。在编译时被去除

RUNTIME:注解存在于类文件里,并且在执行时虚拟机能够获取注解信息

@Retention(RetentionPolicy.<时效值>)

<span style="font-family:SimSun;font-size:18px;">//声明此注解仅仅能对类或者接口进行注解
@Target(ElementType.TYPE)
//声明此注解在执行时能够获得
@Retention(RetentionPolicy.RUNTIME)
@interface myTest{
	//自己定义注解属性
	String msg();
	
}</span>


4.使用反射获取注解

前几篇博客中谈到过反射,在这里也能够通过反射获取到注解的信息,方法与上述类似。

<span style="font-family:SimSun;font-size:18px;">package com.Annotation;

import java.lang.annotation.*;
import java.lang.reflect.*;

//声明使用目标为TYPE的注解
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@interface MyAnnotationForClass {
	java.lang.String msg();
}

// 声明使用目标为METHOD的注解
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@interface MyAnnotationForMethod {
	java.lang.String msgPart1();

	java.lang.String msgPart2();
}

// 声明使用注解的类
@MyAnnotationForClass(msg = "这是对类的注解")
class MyClass {
	@MyAnnotationForMethod(msgPart1 = "方法的第一部分注解", msgPart2 = "方法的第二部分注解")
	public void sayHello() {
		System.out.println("恭喜您成功地调用了sayHello方法!

!"); } } // 主类 public class Sample34_10 { public static void main(String[] args) throws NoSuchMethodException { // 获取使用了注解的类MyClass相应的Class对象 Class ac = MyClass.class; // 获取MyClass类的注解 MyAnnotationForClass mafc = (MyAnnotationForClass) ac .getAnnotation(MyAnnotationForClass.class); // 打印类的注解信息 System.out.println("MyClass类的注解信息为:“" + mafc.msg() + "”。

"); // 获取指定方法相应的Method对象 Method method = ac.getMethod("sayHello", new Class[0]); // 获取方法相应的注解 MyAnnotationForMethod mafm = (MyAnnotationForMethod) method .getAnnotation(MyAnnotationForMethod.class); // 打印方法相应的注解信息 System.out.println("sayHello方法的第一部分注解信息为:“" + mafm.msgPart1() + "”。

"); System.out.println("sayHello方法的第二部分注解信息为:“" + mafm.msgPart2() + "”。"); } } </span>


上述实例中分别定义了两种注解信息。一种应用于类或者接口上。一种应用于方法上面;紧接着通过反射机制获取到对应的注解类,然后就能够操纵注解信息


Java学习笔记十(注解)