码迷,mamicode.com
首页 > 其他好文 > 详细

自定义注解

时间:2019-05-15 20:29:44      阅读:157      评论:0      收藏:0      [点我收藏+]

标签:string   pac   demo   package   strong   float   括号   默认   ret   

自定义注解类格式:

public @interface 注解名 {
    访问权限修饰符 属性类型 属性名称() default 默认值;
    ...
    访问权限修饰属性类型 属性名称() default 默认值; }

 

访问权限修饰符:

  只能使用public或默认(default)这两个。

例如:

String value();
// 或者
public String name();

 

属性类型:

  • 所有基本数据类型(int,float,boolean,byte,double,char,long,short)
  • String类型
  • Class类型
  • enum类型
  • Annotation类型
  • 以上所有类型的数组

属性名称:
  如果只有一个注解属性,可以设置这个注解属性的名称为"value",后加小括号(使用这个注解的时候可以不写value=)。

 

属性值:
  注解元素必须有确定的值,要么在定义注解的默认值中指定,要么在使用注解时指定。非基本类型的注解元素的值不可为null。

 

自定义注解示例:

package com.java.annotation.demo;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Array;
import java.util.Date;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface CustomAnnotation {

    // 注解属性的可支持类型
    
    // 基本数据类型
    byte byteValue() default 0;
    short shortValue() default 0;
    int intValue() default 0;
    long longValue() default 0L;
    float floatValue() default 0F;
    double doubleValue() default 0D;
    char charValue() default ‘a‘;
    boolean booleanValue() default false;
    
    // String类型
    String stringValue() default "";
    
    // Class类型
    Class<?> classValue();
    
    // Annotation类型
    RefAnnotation annotationValue() default @RefAnnotation;
    
    public enum Colour { RED,GREY,GREEN };
    // enum类型
    Colour colorValue() default Colour.RED;

    // 以上所有类型的数组
    byte[] byteArrayValue() default { 1, 2, 3 };
    short[] shortArrayValue() default { 1, 2, 3 };
    int[] intArrayValue() default { 1, 2, 3 };
    long[] longArrayValue() default { 1L, 2L, 3L };
    float[] floatArrayValue() default { 1F, 2F, 3F };
    double[] doubleArrayValue() default { 1D, 2D, 3D };
    char[] charArrayValue() default { ‘a‘, ‘b‘, ‘c‘ };
    boolean[] booleanArrayValue() default { true, false, true };
    
    String[] stringArrayValue() default { "a", "b", "c" };
    
    Class<?>[] classArrayValue() default { Date.class, Array.class };
    
    RefAnnotation[] annotationArrayValue() default { @RefAnnotation };
    
    Colour[] colorArrayValue() default { Colour.RED,Colour.GREEN };
}

使用自定义注解类

package com.java.annotation.test;

import java.util.Date;

import com.java.annotation.demo.CustomAnnotation;

// stringValue的设置与否可选
// classValue必须设置,否则会编译报错,这是因为该注解属性没有设置默认值
@CustomAnnotation(stringValue="huang", classValue = Date.class)
public class TestAnnotation01 {

}

 

自定义注解

标签:string   pac   demo   package   strong   float   括号   默认   ret   

原文地址:https://www.cnblogs.com/517cn/p/10871895.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!