java自定义接口注解,java之自定义注解入门

定义注解与定义接口类似,只是比接口多了个@符号,可以在注解中定义方法,简单例子如下:import java.lang.annotation.ElementType;

import java.lang.annotation.Retention;

import java.lang.annotation.RetentionPolicy;

import java.lang.annotation.Target;

@Description

@Target(ElementType.TYPE)

@Retention(RetentionPolicy.RUNTIME)

public @interface Description {

String value() default "no description";

}

它有以下特性:

1、注解方法不能有参数。

2、注解方法返回值类型局限于原始类型,字符串,枚举,注解或由这些类型组成的数组。

3、注解类型可以包含默认值,如上代码中的default "no description";

4、注解可以包含以下四种元注解:

@Documented –使用该注解的元素将会被javadoc或类似工具文档化,它应用于类型声明,类型声明的注解会影响客户端对注解元素的使用。如果一个类型声明添加了该注解,那么它的注解会成为被注解元素的公共API的一部分。

@Target – 表示支持的注解程序元素种类,可以是TYPE,METHOD,CONSTRUCTOR,FILED等等,如果不写该注解表示不限制,可以使用在任何程序类型上。

@Inherited–表示一个注解类型会被自动继承,如果用户在类声明的时候查询注解类型,同时类声明中也没有这个类型的注解,那么注解类型会自动查询该类的父类,这个过程将会不停地重复,直到该类型的注解被找到为止,或是到达类结构的顶层(Object)。

@Retention– 表示注解类型保留时间长短,它接收RetentionPolicy参数,可能的值有SOURCE, CLASS, 以及RUNTIME。

入门实例:(参考网络)

定义注解:import java.lang.annotation.*;

@Target(ElementType.METHOD)

@Retention(RetentionPolicy.RUNTIME)

@Documented

public @interface Name {

String originate();

String community();

}

注解使用:@Description(value = "JavaEyer,is better")

public class JavaEyer {

@Name(originate = "创始人:abc",community = "javaeye")

public String getEyeName() {

return null;

}

@Name(originate = "创始人:nba",community = "Americ")

public String getSideName() {

return "excuse me";

}

}

测试类:import com.sun.corba.se.impl.orbutil.concurrent.Sync;

import java.lang.reflect.Method;

import java.util.HashSet;

import java.util.Set;

public class AnnotationTest {

@SuppressWarnings("uncheked")

public static void main(String[] args) {

final String CLASS_NAME = "JavaEyer";

try {

Class test = Class.forName(CLASS_NAME);

Method[] methods = test.getMethods();

boolean flag = test.isAnnotationPresent(Description.class);

if(flag){

Description des = (Description)test.getAnnotation(Description.class);

System.out.println("描述:"+des.value());

System.out.println("----------------------------");

}

Set set = new HashSet();

for(int i = 0;i

boolean otherflag = methods[i].isAnnotationPresent(Name.class);

if(otherflag){

set.add(methods[i]);

}

}

for(Method method:set){

Name name = method.getAnnotation(Name.class);

System.out.println(name.originate());

System.out.println("创建的社区:"+ name.community());

}

} catch (ClassNotFoundException e) {

e.printStackTrace();

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值