一、内置注解
1)@Override:重写方法
2)@Deprecated:遗弃的(不推荐使用)
3)@SuppressWarnings:压制编译时的警告信息
都定义在Java的lang包中。
二、自定义注解(在一个包上右击-->new-->javaclass-->下翻找到annotation-->输入name)
1、自定义注解
1)定义类的注解
package com.bjsxt.test.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(value={ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface SxtTable {
String value();
}
2)定义属性的注解
package com.bjsxt.test.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(value=ElementType.FIELD)//使用范围
@Retention(RetentionPolicy.RUNTIME)//生命周期
public @interface SxtField {
String columnName();
String type();
int len();
}
2、使用自定义注解
package com.bjsxt.test.annotation;
@SxtTable("tb-table")
public class SxtStudent {
@SxtField(columnName ="id",type="int",len=10 )
private int id;
@SxtField(columnName ="name",type="String",len=10 )
private String name;
@SxtField(columnName ="age",type="int",len=3 )
private int age;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
3、得到注解
package com.bjsxt.test.annotation;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
public class Demon03 {
public static void main(String[] args) {
try {
Class clazz=Class.forName("com.bjsxt.test.annotation.SxtStudent");
//获得该类的所有注解
Annotation[] annotations=clazz.getAnnotations();
for( Annotation a:annotations){
System.out.println(a);
}
//获得类的指定的注解
SxtTable st=(SxtTable) clazz.getAnnotation(SxtTable.class);
System.out.println(st.value());
//获得类的属性的注解
Field f=clazz.getDeclaredField("name");
SxtField sxtfield=f.getAnnotation(SxtField.class);
System.out.println(sxtfield.columnName());
//根据获得的类名、字段的信息,拼出DDL语句,使用JDBC执行这个SQL,在数据库中生成相对应的表
} catch (ClassNotFoundException | NoSuchFieldException e) {
e.printStackTrace();
}
}
}