Java基本注解

常用注解

@Override 继承父类

@Deprecated 方法已经过时

@SupperessWarnings(“depresscated) 忽略警告

注解分类

  • 1、源码注解 只存在于源码中,编译成.class文件就不存在了。
  • 2、编译时注解 在源码和.class 文件中存在的注解。
  • 3、运行时注解 在运行阶段还起作用,甚至会影响运行逻辑。
1
2
3
4
5
6
7
8
9
@Target({ElementType.METHOD,ElementType.TYPE})
@Retantion(RetentionPolicy>RUNTIME)
@Inherited
@Documented
public @interface Description{
String desc();
String author();
int age() default 18;
}
  • 1、成员类型是受限的,合法的类型包括原始类型及StringClass ,Annotation ,Enumeration。
  • 2、如果只有一个成员的时候,成员名必须取名为value(),在使用时可以忽略成员名和赋值号(=)。
  • 3注解类可以没有成员,没有成员的注解叫做标示注解。

元注解

@Target 注解作用域

constructor     构造方法声明
file        文件声明
local variable      局部变量声明
method      方法申明
package     包申明

parameter   参数申明
type        类接口

@Retention 生命周期

source  只在源码中显示,编译时丢弃
class       编译时会记录到class中,运行时忽略
runtime 运行时存在,可通过反射获取

@Inherited 允许子类继承
@Docunmented 生成javadoc时包含注解的信息

自定义注解的使用

@<注解名>(<成员名1>=<成员值1>,<成员名2>=<成员值2>,……)

1
2
3
4
@Description(desc=“I am eyeColor”, author=“Mooc boy” ,age=18) 		
public String eyeColor(){
return “red”;
}

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
@Table("pzh")
public class User {
@Column("name1")
private String name;
@Column("nickName1")
private String nickName;
@Column("age1")
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getNickName() {
return nickName;
}
public void setNickName(String nickName) {
this.nickName = nickName;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}

}
public class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
User user = new User();
user.setName("zjp");
show(user);
}
private static void show(User user) {
Class class1 = user.getClass();
boolean isExit = class1.isAnnotationPresent(Table.class);
if (isExit) {
Table table = (Table) class1.getAnnotation(Table.class);
System.out.println("table value=" + table.value());
}
Field[] files = class1.getDeclaredFields();
for (Field field : files) {
if (field.isAnnotationPresent(Column.class)) {
Column column = field.getAnnotation(Column.class);
System.out.println("column value=" + column.value());
System.out.println("file name=" + field.getName());
String filedName=field.getName();
String methodNme="get"+filedName.substring(0, 1).toUpperCase()+filedName.substring(1);
try {
Method method=class1.getMethod(methodNme);
Object fileValue=method.invoke(user,null);
System.out.println("file value=" + fileValue);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}