java Annotation(注解)

本文详细介绍了Java注解的创建及使用方法,包括自定义注解、元注解(如@Target、@Retention、@Documented、@Inherited)的应用场景,并通过示例展示了如何解析类上的注解。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、申明一个注解类、用到关键字interface 前面加个@

public @interface myAnnotation

2、添加成员、可以看成接口的方法。类型 成员名称+();

String name();

String value();

 

3、使用 Target 元注释、避免他人误用您的注释类型、 应用于类型、方法、构造函数和其他注释类型

@Target({

         ElementType.TYPE,

         ElementType.METHOD,

         ElementType.CONSTRUCTOR,

         ElementType.ANNOTATION_TYPE

})

4、使用 Retention 元注释

  4、1  RUNTIME  编译后在class文件中程序可以读到

  4、2  SOURCE   不在编译的class文件中程序不能读到

5、Documented

    Documented 表示注释应该出现在类的 Javadoc 中。

6、使用 Inherited 元注释

  添加 @Inherited 后,您将看到 InProgress 出现在注释类的子类中

 

 

demo

 

myAnnotation.class

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

@Retention(RetentionPolicy.RUNTIME)
public @interface myAnnotation{
	String name();
	String value();
}

 

 

使用

 

@myAnnotation(name="table",value="12313")
class User extends Person{
	
}

 

main 

                public static void main(String[] args) throws Exception {
		Annotation[] anns=User.class.getAnnotations();
		int i=0;
		int len=anns.length;
		for(i=0;i<len;i++){
			System.out.println(anns[i]);
		}
	}

 

结果:

@test.myAnnotation(name=table, value=12313)

 

 

 

 

注解应用:

1、 JPA javax.persistence

2、 spring 注入注解

等等。。。

 

 

 

http://blog.sina.com.cn/s/blog_61f4999d0100l26e.html java注解应用

http://blog.youkuaiyun.com/hbzyaxiu520/archive/2011/02/28/6212969.aspx JAVA自定义注释(Target,Retention,Documented,Inherit)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值