注解的详解和自定义

来源:互联网 发布:淘宝标题优化技巧 编辑:程序博客网 时间:2024/06/14 11:37
什么是注解?
注解不是注释(comment:注释)是jdk1.5后出现的新技术。
Annotation的作用?
不是程序本身,可以对程序作出解释。(注释的作用)
可以被其他程序读取
Annotation的格式?
注解是以“@注释名”在代码中存在,还可以添加一些参数值。
Annotation的使用范围?
可以注解在方法,类,属性上面。
内置注解(1)
@Override 重写的注解。
详谈@Override源代码如下:
@Target(ElementType.METHOD)//只用于方法前面
@Retention(RetentionPolicy.SOURCE)//保留
public @interface Override{
}
@Deprecated 不推荐使用注解。


@SuppressWarnings 注解中的参数写法 SuppressWarnings中String[] values();这就是参数类型String[]和values()参数;
详谈@SuppressWarnings 源代码如下:让我们的代码更加清爽。
@Target({TYPE,FIELD,METHOD,PARAMETER,CONSTRUCTOR,LOCAL_VARIBALE})//可以用于类型,方法,文件,枚举前面
@Retention(RetentionPolicy.SOURCE)
public @interface SuppressWarnings{
String[] values();
}
怎么样自定义注解:
@Target 用于描述注解的使用范围(即:被描述的注解可以用在什么地方)。
@Retention 保留的策略。RetentionPolicy,SOURCE(在源文件中有效) ,CLASS(在类中有效),RUNTIME(在运行时有效)。
下面一个自定义注解类的范例:
@Target(value={ElementType.METHOD,ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME);
public @interface SxtAnnotation01{
Sting stuName() default "";
int age default 0;
int id default -1;
String [] schools() default{"清华大学","北京尚学堂"};
}
下面第二个之定义注解
@Target(value={ElementType.METHOD,ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface SxtAnnotation02{
String value();//若只有一个参数的话就直接应用为value
}
注解在另外一个类中的使用:
@SxtAnnotation01
public class Demo02{
@SxtAnnotation01(age=19,studentName="老高",id="0010" schools={"beida","qinghua"})
public void test01(){

}
@SxtAnnotation02("aaa")//没有默认值就会要求添加值,他可以这样写例如@SxtAnnotation02(value=“aaa”)
public void test02(){

}
}
注解的作用,注解的作用则需要解析才会产生作用。(后面文章会提及到反射机制解析注解)
0 0