注解: Annotation
1、内置注解:常见的三种内置注解
1)、@Override 表示长些超类中的方法
2)、@Deprecated 表示不建议使用的元素
3)、SuppressWarnings 表示抑制程序中的一些警告
2、元注解(meta-annotation):java.lang.annotion中定义了4个标准的元注解,(前两个常用)
1)、@Target 表示注解的使用地点
2)、@Retention 注解可以被读取的范围
3)、@Documented
4)、@Inherited
自定义注解格式:
元注解(作用是来解释自定义注解)
public @interface 类名{
参数
}
注意事项:
1、自定义注解时通常需要指定default值,如0,“”(空字符串),-1(表示不存在)
2、如果不指定默认值,使用时就要添加,否者报错
3、如果自定义注解只有一个参数,建议起名为value
4、注意一下参数的形式 eg:String[] value() 看起来想函数,其实表示字符串数组
package com.chen.annotation01;
import java.util.Date;
/**
* 认识一下常用的一些注解
* @author Administrator
*
*/
public class Demo01 {
// 重写方法
@Override
public String toString() {
return "我重写的";
}
public static void main(String[] args) {
Date data = new Date();
// 不建议使用的方法
data.parse("dsacd");
}
@SuppressWarnings(value = { "all" })// value参数除了all外还有:deprecation、unchecked、finally....
public void test01() {
Date data = new Date();
// 这里就不警告了
data.parse("dsacd");
}
}
package com.chen.annotation01;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* 自定义注解
* @author Administrator
*
*/
@Target(value = {ElementType.FIELD, ElementType.METHOD})// 适用于注解方法和属性,还有其他类型
@Retention(value = RetentionPolicy.RUNTIME)// 还有其他两种类型CLASS、SOURCE 但这种作用范围最广
public @interface MyAnnotation {
String str() default "";
int id() default 0;
int x() default -1;
String[] value();
}
package com.chen.annotation01;
/**
* 测试自定义注解
* @author Administrator
*
*/
//报错,因为@MyAnnotation定义为只能用于方法和属性前面
//@MyAnnotation(id = 1, value = { "aaa" })
public class TestMyAnnotation {
public static void main(String[] args) {
}
@MyAnnotation(id = 1, value = { "aaa" })// 由于value没有设置默认值,这里就必须指定
public static void test01() {
}
}