//学了很多框架后,一直使用注解,一直明白其中的原理,只知道是用了反射的原理
//今天看了一下,决定很简单。注解为了简化编程,给某个东西起啦个名字,当把这个名字贴到某个地方,这个地方就这个名字的相关意义。
//当你想知道这个地方的相关意义时,你可以通过反射获得该类,然后获得这个名字,通过名字获得这个地方的相关意义。
//下面这篇博客讲的很详细
https://blog.csdn.net/briblue/article/details/73824058
下面是一个小例子:如果你使用过hibernate或者springBoot中使用JPA就很容易理解下面的例子
定义一个table类注解
@Documented
@Retention(RUNTIME)
@Target({ TYPE, FIELD })
public @interface table {
String value(); }
定义了一个culumn注解
@Documented
@Retention(RUNTIME)
@Target({FIELD})
public @interface culumn {
String value(); }
Person类中使用上面两个注解
@table("person")
public class Person {
@culumn("name")
private String name;
@culumn("age")
private String age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
}
下面使用的测试:
public class client {
public static void main(String[] args) {
try {
String age="23";
String name="dfd";
StringBuffer buffer = new StringBuffer();
Class<Person> o=(Class<Person>) Class.forName("com.mao.Person");
System.out.println(o);
table t= o.getAnnotation(table.class);
buffer.append("select * from "+t.value());
System.out.println(o.getSimpleName());
Field f[]=o.getDeclaredFields();
System.out.println(o.isAnnotationPresent(table.class));
System.out.println(o.getAnnotation(table.class));
culumn a= f[0].getAnnotation(culumn.class);
buffer.append(" where "+a.value()+"="+name);
buffer.append(" and ");
a= f[1].getAnnotation(culumn.class);
buffer.append(a.value()+"="+age);
System.out.println(buffer);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}