【Java EE 学习 24 上】【注解详解】
一、注解
1.所有的注解都是类。
2.所有的注解都是Annotation接口的子类。
接口摘要 |
|
所有 annotation 类型都要扩展的公共接口。 |
3.定义方式
public @interface TestAnnotation { }
4.可以注解的位置:任何地方都可以,但是要满足注解的具体限制,默认注解可以加在任意位置上
package com.kdyzm.anotation; @TestAnnotation
public class Test {
@TestAnnotation
private String name; @TestAnnotation
public void show(@TestAnnotation String name)
{
@TestAnnotation
String age;
System.out.println(name);
}
}
5.使用注解限制注解的位置
使用@Target注解限制自定义注解的注解位置。
@Target(value={ElementType.METHOD})//声明只能对方法进行注解,接收数组参数
具体可以限制的类型:ElementType枚举
/*
* %W% %E%
*
* Copyright (c) 2006, Oracle and/or its affiliates. All rights reserved.
* ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/ package java.lang.annotation; /**
* A program element type. The constants of this enumerated type
* provide a simple classification of the declared elements in a
* Java program.
*
* <p>These constants are used with the {@link Target} meta-annotation type
* to specify where it is legal to use an annotation type.
*
* @author Joshua Bloch
* @since 1.5
*/
public enum ElementType {
/** Class, interface (including annotation type), or enum declaration */
TYPE, /** Field declaration (includes enum constants) */
FIELD, /** Method declaration */
METHOD, /** Parameter declaration */
PARAMETER, /** Constructor declaration */
CONSTRUCTOR, /** Local variable declaration */
LOCAL_VARIABLE, /** Annotation type declaration */
ANNOTATION_TYPE, /** Package declaration */
PACKAGE
}
ElementType.java
6.限制注解在运行时是否删除
使用@Retention限制注解的存在范围
@Retention(value=RetentionPolicy.RUNTIME)//声明该注解在运行时保存,即使用方法isAnnotationPresent方法返回值是true
具体的参数见:RetentionPolicy枚举(保留策略枚举)。
/*
* %W% %E%
*
* Copyright (c) 2006, Oracle and/or its affiliates. All rights reserved.
* ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/ package java.lang.annotation; /**
* Annotation retention policy. The constants of this enumerated type
* describe the various policies for retaining annotations. They are used
* in conjunction with the {@link Retention} meta-annotation type to specify
* how long annotations are to be retained.
*
* @author Joshua Bloch
* @since 1.5
*/
public enum RetentionPolicy {
/**
* Annotations are to be discarded by the compiler.
*/
SOURCE, /**
* Annotations are to be recorded in the class file by the compiler
* but need not be retained by the VM at run time. This is the default
* behavior.
*/
CLASS, /**
* Annotations are to be recorded in the class file by the compiler and
* retained by the VM at run time, so they may be read reflectively.
*
* @see java.lang.reflect.AnnotatedElement
*/
RUNTIME
}
RetentionPolicy.java
7.注解的作用
(1)编译时限制作用
public class MyServlet extends HttpServlet {
@Override
public void doGet(ServletRequest req,String name)
throws ServletException, IOException {
}
}
因为父类没有这个方法,所以加上@Override注解之后就会编译报错。
(2)运行时反射
所有类的字节码对象Class、Field、Method、Constructor都拥有一个方法
|
|
|
|
默认自定义注解在运行时删除,但是通过其它注解可以定义该自定义注解的生存范围。怎样定义见6。
8.注解的实例化
永远不要实例化注解类,因为注解类是通过系统通过反射实例化的。
9.给注解定义属性/方法(官方说法为属性)。
(1)value属性:官方推荐的属性,也是默认的属性,使用方法:public String value();(这种定义方法看上去好像是方法,但是实际上是属性,暂且为属性)
(2)修饰符必须是public,可以存在static、final修饰,但是不能有其它修饰符。
(3)默认值:使用关键字default定义,如果没有设置默认值,则在使用注解的时候必须显示赋值才能通过编译。
10.注解定义示例。
package com.kdyzm.anotation; import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target; @Target(value={ElementType.METHOD})//声明只能对方法进行注解,接收数组参数
@Retention(value=RetentionPolicy.RUNTIME)//声明该注解在运行时保存,即使用方法isAnnotationPresent方法返回值是true
public @interface MyAnnotation {
public String value();
public String name() default "noName";
}
二、使用注解小示例。
1.获取注解的属性值。
使用Class类、Field类、Method类、Constructor类的getAnnotation方法。
|
||
|
|
2.自定义注解小练习。
(1)自定义注解MyAnnotation
package com.kdyzm.anotation; import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target; @Target(value={ElementType.METHOD})//声明只能对方法进行注解,接收数组参数
@Retention(value=RetentionPolicy.RUNTIME)//声明该注解在运行时保存,即使用方法isAnnotationPresent方法返回值是true
public @interface MyAnnotation {
public String value();
public String name() default "noName";
}
(2)在UseMyAnnotation类中使用自定义注解
package com.kdyzm.setOnMyAnnotation; import com.kdyzm.anotation.MyAnnotation;
//使用自定义注解,该注解只能加在方法上。
public class UseMyAnnotation {
private String name;
private int age;
@MyAnnotation("setName方法")
public void setName(String name)
{
this.name=name;
}
@MyAnnotation("getName方法")
private String getName()
{
return name;
}
private int getAge()
{
return age;
}
@MyAnnotation("setAge方法")
public void setAge(int age)
{
this.age=age;
}
}
(3)解析UseMyAnnotation类的所有内容并对注解进行解析。
package com.kdyzm.demo; import java.lang.reflect.Method;
import java.lang.reflect.Modifier; import com.kdyzm.anotation.MyAnnotation; //测试自定义注解MyAnnotation的使用,使用MyAnnotation类和UseMyAnnotation类两个类
public class MyTest {
public static void main(String[] args) throws Exception {
String className="com.kdyzm.setOnMyAnnotation.UseMyAnnotation";
Class cls=Class.forName(className);
//实例化该类。
Object obj=cls.newInstance(); //获取该类中的所有方法
Method []methods=cls.getDeclaredMethods();
//遍历该方法数组。
for(Method method:methods)
{
boolean flag=method.isAnnotationPresent(MyAnnotation.class);//判断是否进行了方法的注解
if(flag)//如果进行了方法的注解
{
System.out.print("被注解的方法:");
//判断是否是私有的方法
if(method.getModifiers()==Modifier.PRIVATE)
{
//如果是私有的方法则设置暴力破解
method.setAccessible(true);
System.out.println("该方法私有!方法名为:"+method.getName());
}
else
{
System.out.println("该方法共有!方法名为:"+method.getName());
} //如果被注解了,输出该注解属性值
MyAnnotation annotation=method.getAnnotation(MyAnnotation.class);
String value=annotation.value();
String name=annotation.name();
System.out.println("该注解的内容是:"+value+","+name);
}
else//说明是没有被注解的方法
{
System.out.print("没有被注解的方法:");
//判断是否是私有的方法
if(method.getModifiers()==Modifier.PRIVATE)
{
//如果是私有的方法则设置暴力破解
method.setAccessible(true);
System.out.println("该方法私有!方法名为:"+method.getName());
}
else
{
System.out.println("该方法共有!方法名为:"+method.getName());
}
}
System.out.println();
}
}
}
(4)运行结果。
没有被注解的方法:该方法私有!方法名为:getAge 被注解的方法:该方法共有!方法名为:setAge
该注解的内容是:setAge方法,noName 被注解的方法:该方法私有!方法名为:getName
该注解的内容是:getName方法,noName 被注解的方法:该方法共有!方法名为:setName
该注解的内容是:setName方法,noName
【Java EE 学习 24 上】【注解详解】的更多相关文章
- 【Java EE 学习 74 上】【数据采集系统第六天】【使用Jfreechart的统计图实现】【Jfreechart的基本使用方法】
之前已经实现了数据的采集,现在已经有了基本的数据,下一步就需要使用这些数据实现统计图的绘制了.这里使用Jfreechart实现这些统计图的绘制.首先看一下Jfreechart的基本用法,只有知道了它的 ...
- 【Java EE 学习 80 上】【WebService】
一.WebService概述 什么是WebService,顾名思义,就是基于Web的服务,它使用Http方式接收和响应外部系统的某种请求,从而实现远程调用.WebService实际上就是依据某些标准, ...
- 【Java EE 学习 78 上】【数据采集系统第十天】【Service使用Spring缓存模块】
一.需求分析 调查问卷中或许每一个单击动作都会引发大量的数据库访问,特别是在参与调查的过程中,只是单击“上一页”或者“下一页”的按钮就会引发大量的查询,必须对这种问题进行优化才行.使用缓存策略进行查询 ...
- 【Java EE 学习 25 上】【网上图书商城项目实战】
一.概述 1.使用的jdk版本:1.6 2.java EE版本:1.6 3.指导老师:传智播客 王建 二.小项目已经实现的功能 普通用户: 1.登陆 2.注册 3.购物 4.浏览 管理员用户(全部管理 ...
- 【Java EE 学习 24 下】【注解在数据库开发中的使用】【反射+注解+动态代理在事务中的应用service层】
一.使用注解可以解决JavaBean和数据库中表名不一致.字段名不一致.字段数量不一致的问题. 1.Sun公司给jdbc提供的注解 @Table.@Column.@Id.@OneToMany.@One ...
- 【Java EE 学习 83 上】【SpringMVC】【基本使用方法】
一.SpringMVC框架概述 什么是SpringMVC?SpringMVC是一个和Struts2差不多的东西,他们的作用和性质几乎是相同的,甚至开发效率上也差不多,但是在运行效率上SpringMVC ...
- 【Java EE 学习 67 上】【OA项目练习】【JBPM工作流的使用】
OA项目中有极大可能性使用到JBPM框架解决流程控制问题,比如请假流程.报销流程等等. JBPM:JBoss Business Process Management,翻译过来就是业务流程管理.实际上就 ...
- 【Java EE 学习 82 上】【MAVEN基本安装和使用方法】
一.Maven概述 1.什么是Maven? Maven中文意思是"行家"."专家",它是一种跨平台的项目管理工具. 2.Maven有什么作用? Maven能够实 ...
- 【Java EE 学习 77 上】【数据采集系统第九天】【通过AOP实现日志管理】【通过Spring石英调度动态生成日志表】【日志分表和查询】
一.需求分析 日志数据在很多行业中都是非常敏感的数据,它们不能删除只能保存和查看,这样日志表就会越来越大,我们不可能永远让它无限制的增长下去,必须采取一种手段将数据分散开来.假设现在整个数据库需要保存 ...
随机推荐
- js在手机端不能正确显示
在html页面head中加入<meta name="viewport" content="width=device-width, initial-scale=1.0 ...
- oneThink后台添加插件步骤详解
内容管理框架:oneThink 版本:V1.1.141212 (注:v1.1也有很多版本,一不小心就下到V1.1.140202 去了,还有其他版本,建议去代码托管平台下载最新版本) 我也不偷懒,把每一 ...
- redis配置详解
##redis配置详解 # Redis configuration file example. # # Note that in order to read the configuration fil ...
- COGS746. [网络流24题] 骑士共存
骑士共存问题«问题描述:在一个n*n个方格的国际象棋棋盘上,马(骑士)可以攻击的棋盘方格如图所示.棋盘 上某些方格设置了障碍,骑士不得进入. «编程任务:对于给定的n*n个方格的国际象棋棋盘和障碍标志 ...
- shell中$0,$?,$!等的特殊用法
变量说明: $$Shell本身的PID(ProcessID)$!Shell最后运行的后台Process的PID$?最后运行的命令的结束代码(返回值)$-使用Set命令设定的Flag一览$*所有参数列表 ...
- Mybatis传参数
1使用@Param注解传参数 mapper接口:public void updateUser(@Param("user")User user)throws Exception; m ...
- webmagic 增量爬取
webmagic 是一个很好并且很简单的爬虫框架,其教程网址:http://my.oschina.net/flashsword/blog/180623 webmagic参考了scrapy的模块划分, ...
- cinnamon桌面安装在其他目录下
cinnamon桌面还不错,不过默认只能安装在/usr目录下 有很多脚本中写死了是/usr目录 编译时如下模块需要打补丁: 1.cinnamon中,需要执行 sed -i 's|usr/share|u ...
- Linux终端最常用快捷键
新建终端窗口: crtl+shift+N 终端的漂移/切换:shift+左右箭头 挂 起:crtl+s 解除挂起:crtl+q 清 屏:crtl+l 命令行光标移动: crtl+a 移动到命令行首 c ...
- 搭建XMPP学习环境
XMPP(Extensible Messaging and Presence Protocol,前称Jabber)是一种以XML为基础的开放式IM协议.xmpp被人熟知,google talk肯定有一 ...