java注解

来源:互联网 发布:java poi jar 编辑:程序博客网 时间:2024/05/01 01:42

java注解

1.什么是注解: 

        可以理解为一种标记,程序在添加标记的地方可以进行相关解释操作.

        生命周期:注解保存到java源码中,注解保存到编译class文件阶段(注解默认),注解保存到class文件加载到内存中

Java SE5内置了三种标准注解:

     @Override,表示当前的方法定义将覆盖超类中的方法。

     @Deprecated,使用了注解为它的元素编译器将发出警告,因为注解@Deprecated是不赞成使用的代码,被弃用的代码。

     @SuppressWarnings,关闭不当编译器警告信息。


public enum ElementType
extends Enum<ElementType>
2.怎样使用注解:

注解实现的接口

ElementType
ANNOTATION_TYPE
          注释类型声明CONSTRUCTOR
          构造方法声明FIELD
          字段声明(包括枚举常量)LOCAL_VARIABLE
          局部变量声明METHOD
          方法声明PACKAGE
          包声明PARAMETER
          参数声明TYPE
          类、接口(包括注释类型)或枚举声明

        1.创建注解的标记类

package com.test;import java.lang.annotation.ElementType;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;@Retention(RetentionPolicy.RUNTIME)@Target({ElementType.METHOD,ElementType.TYPE})public @interface AddThread {    public abstract String startTime() default "run";    public abstract String value();    public abstract String [] point() default {"0","1"};    public abstract MethodAttr meth() default @MethodAttr("meth,hehe");    }
package com.test;public @interface MethodAttr {String value();}



        2.为类添加注解

        3.为注解写解释类

package com.test;@AddThread(startTime="runClass",value="hehe",point={"1","2"},meth=@MethodAttr("gaga"))public class PrintCode {@AddThread("haha")public void printcode(String code){System.out.println(code);}public static void main(String[] args) throws SecurityException, NoSuchMethodException {// 获取添加注解类的字节码Class<?> cla=com.test.PrintCode.class;//检查是否添加了注解boolean annotationPresent = cla.isAnnotationPresent(AddThread.class);    if(annotationPresent){    //得到注解    AddThread annotation = PrintCode.class.getAnnotation(AddThread.class);    AddThread annotation2 = PrintCode.class.getMethod("printcode", String.class).getAnnotation(AddThread.class);    System.out.println(annotation.startTime());    System.out.println(annotation2.startTime());    System.out.println(annotation2.point());    }}}


        

0 0
原创粉丝点击