@SuppressWarnings(value="unchecked")
作用在代码的注解是
作用在其他注解的注解(或者说 元注解)是:
[@interface](#)
用来声明一个注解,格式:public?@interface 注解名{定义内容}
public class Test02 {
/**
* 注解可以显示赋值,如果没有默认值,就必须给注解赋值
*/
@MyAnnotation2(name = "Hello")
public void test(){};
}
@Target({ElementType.METHOD,ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation2{
//注解的参数:参数类型 + 参数名();
String name() default "";
int age() default 0;
int id() default -1;//如果默认值为-1,表示不存在
String[] schools() default {"A","B"};
}
@Target({ElementType.METHOD,ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation3{
String value();
}
public class Test11 {
public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException {
Class c1 = Class.forName("study.reflection.Student2");
//通过反射获得注解
Annotation[] annotations = c1.getAnnotations();
for (Annotation annotation : annotations) {
System.out.println(annotation);
}
//获得注解的value的值
tableTest tabletest = (tableTest)c1.getAnnotation(tableTest.class);
String value = tabletest.value();
System.out.println(value);
//获得类指定的注解
Field name = c1.getDeclaredField("name");
FieldTest annotation = name.getAnnotation(FieldTest.class);
System.out.println(annotation.columnName());
System.out.println(annotation.length());
System.out.println(annotation.type());
}
}
@tableTest("db_student")
class Student2 {
@FieldTest(columnName = "db_name",type="varchar",length=3)
private String name;
@FieldTest(columnName = "db_id",type="int",length=10)
private int id;
@FieldTest(columnName = "db_age",type="int",length=10)
private int age;
public Student2() {
}
public Student2(String name, int id, int age) {
this.name = name;
this.id = id;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Student2{" +
"name=‘" + name + ‘\‘‘ +
", id=" + id +
", age=" + age +
‘}‘;
}
}
/**
* @author zhao
* 类名的注解
*/
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@interface tableTest{
String value();
}
/**
* @author zhao
* 属性的注解
*/
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@interface FieldTest{
String columnName();
String type();
int length();
}
原文:https://www.cnblogs.com/goodluckya/p/12751607.html