注解
注解(Annotation)
作用:
1.不是程序本身 , 可以对程序作出解释.(这一点和注释(comment)没什么区别)
2.可以被其他程序(比如:编译器等)读取
格式:
注解是以"@注释名"在代码中存在的 , 还可以添加一些参数值 , 例如:@SuppressWarnings(value=“unchecked”).
在哪里使用?
可以附加在package , class , method , field 等上面 , 相当于给他们添加了额外的辅助信息, 我们可以通过反射机制编程实现对这些元数据的访问
内置注解
@Override : 定义在 java.lang.Override 中 , 此注释只适用于修辞方法 , 表示一个方法声明打算 重写超类中的另一个方法声明.
@Deprecated : 定义在java.lang.Deprecated中 , 此注释可以用于修辞方法 , 属性 , 类 , 表示不 鼓励程序员使用这样的元素 , 通常是因为它很危险或者存在更好的选择
@SuppressWarnings : 定义在java.lang.SuppressWarnings中,用来抑制编译时的警告信息. p 与前两个注释有所不同,你需要添加一个参数才能正确使用,这些参数都是已经定义好了的, 我们选择性的使用就好了 .
1) @SuppressWarnings(“all”)
2) @SuppressWarnings(“unchecked”)
3) @SuppressWarnings(value={“unchecked”,“deprecation”})
元注解
元注解的作用就是负责注解其他注解 , Java定义了4个标准的meta-annotation类型,他们被用来 提供对其他annotation类型作说明 .
这些类型和它们所支持的类在java.lang.annotation包中可以找到 .( @Target , @Retention , @Documented , @Inherited )
@Target : 用于描述注解的使用范围(即:被描述的注解可以用在什么地方)
@Retention : 表示需要在什么级别保存该注释信息 , 用于描述注解的生命周期 Ø (SOURCE < CLASS < RUNTIME)
@Document:说明该注解将被包含在javadoc中
@Inherited:说明子类可以继承父类中的该注解
自定义注解
使用@interface自定义注解时 , 自动继承了java.lang.annotation.Annotation接口
解析:
@ interface用来声明一个注解 , 格式 : public @ interface 注解名 { 定义内容 }
其中的每一个方法实际上是声明了一个配置参数.
方法的名称就是参数的名称.
返回值类型就是参数的类型 ( 返回值只能是基本类型,Class , String , enum ).
可以通过default来声明参数的默认值
如果只有一个参数成员 , 一般参数名为value
注解元素必须要有值 , 我们定义注解元素时 , 经常使用空字符串,0作为默认值
public @interface Action { // 无属性值
}
public @interface Action { // 有属性值
String action() default "A";
int value() default 0;
}
声明2个注解
@Target(ElementType.CONSTRUCTOR)
@Retention(RetentionPolicy.RUNTIME)
public @interface Action {
String action() default "构造函数";
}
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface FieldAnnotation {
String describe() default "描述";
Class type() default void.class;
}
注解@Action 使用于构造函数,有一个描述属性,@FieldAnnotation适用于注解属性常量,包含一个String类型的描述和修饰的类型
使用:
public class ConstructorExample {
@FieldAnnotation(describe = "名字" ,type = String.class)
public String name;
@FieldAnnotation(describe = "分数",type = int.class)
protected int core;
@Action()
public ConstructorExample(String name, int core) throws NumberFormatException {
this.core = core;
this.name = name;
}
}
反射( Reflection)
Reflection(反射)是Java被视为动态语言的关键,反射机制允许程序在执行期借 助于Reflection API取得任何