@SuppressWarnings(value="unchecked")
//压制提示
@SuppressWarnings("all")
public class Demo01 {
//重写注解 如果方法名不对会报酬
@Override
public String toString() {
return "";
}
//不建议使用 会出现横线,但仍可以执行
@Deprecated
public static void test001() {
System.out.println("test001");
}
public static void test002() {
List list = new ArrayList();
List list2 = new ArrayList();
}
}
元注解
@Target 注解使用范围 TYPE FIELD METHOD PARAMETER CONSTRUCTOR LOCAL_VARIABLE ANNOTATION_TYPE PACKAGE TYPE_PARAMETER TYPE_USE
@Retention 保留策略,用于描述注解的生命周期
SOURCE 源文件中有效
CLASS class文件中有效
RUNTIME 运行时有效,可以为反射读取
@Target(value= {ElementType.METHOD,ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation_1 {
String name() default "";
int age() default 0;
int id() default -1;
String[] schools() default {"青花大学","北京大学"};
}
@MyAnnotation_1(name="yuankun",age=35,schools= {"石油大学","清华大学"})
public static void test002() {
List list = new ArrayList();
List list2 = new ArrayList();
}
如果参数只有一个,一般定义为 String value()
;
@Target(value= {ElementType.METHOD,ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation_2 {
String value();
}
@MyAnnotation_2("aaa")
public static void test003() {
return;
}
public class MyORM {
public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, SecurityException {
Class clazz = Class.forName("com.niliv.demo.Student");
//获取的类的所有注解
Annotation[] annotations = clazz.getAnnotations();
for (Annotation annotation : annotations) {
System.out.println(annotation); //@com.niliv.demo.Table(value=tb_student)
}
//获取类的注解值
Table table = (Table)clazz.getAnnotation(Table.class);
System.out.println(table.value()); //tb_student
java.lang.reflect.Field field = clazz.getDeclaredField("sname");
Field field2 = field.getAnnotation(Field.class);
System.out.println(field2.columnName() +"--"+field2.type()+"--"+field2.length());
System.out.println("tableName: " + table.value());
System.out.println("field:"+field2.columnName() +"--"+field2.type()+"--"+field2.length());
}
}
@Table("tb_student")
public class Student {
@Field(columnName="id",type="int",length=10)
private int id;
@Field(columnName="sname",type="varchar",length=10)
private String sname;
@Field(columnName="age",type="int",length=3)
private int age;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getSname() {
return sname;
}
public void setSname(String sname) {
this.sname = sname;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
@Target(value= {ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface Table {
String value();
}
@Target(value= {ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Field {
String columnName();
String type();
int length();
}