什么是注解?
jdk1.5新增新技术,注解,很多框架为了简化代码,都会提供有些注解。可以理解为插件,是代码级别的插件,注解不会影响代码的实际逻辑,仅仅起到辅助性作用。
注解分类:内置注解,自定义注解
内置注解
@SuppressWarnings:再程序前面加上可以在javac编译中去除警告。
@Deprecated:带有标记的包,方法,字段说明其过时。
@Overricle:打上这个标记说明该方法是将父类的方法重写。
自定义注解
元注解的作用就是负责注解其他注解。
@Target说明了Annotation所修饰的对象范围。
@Retention:表示需要在说明级别保存该注释信息,用于描述注解的生命周期。
@Target(value = {ElementType.METHOD,ElementType.FIELD,ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation {
String name() default "";
int age() default 0;
}
//使用
@MyAnnotation(name= "wenlong", age = 10)
public class Demo {
}
实现ORM框架映射
//自定义注解
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@interface MyTable {
String name();
}
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@interface MyField {
String name();
}
//配置实体类
@MyTable(name = "tb_table")
class Person {
@MyField(name = "tb_name")
private String name;
@MyField(name = "tb_age")
private String age;
}
//手动实现aop
public class Demo {
public static void main(String[] args) throws Exception {
Class<?> clazz = Class.forName("com.shuwenlong.thread.Person");
StringBuffer sb = new StringBuffer();
sb.append("select ");
Field[] fields = clazz.getDeclaredFields();
for(int i=0; i<fields.length; i++) {
MyField myField = fields[i].getDeclaredAnnotation(MyField.class);
String name = myField.name();
sb.append(name);
if(i != fields.length -1) {
sb.append(",");
}
}
MyTable myTable = clazz.getDeclaredAnnotation(MyTable.class);
sb.append(" from " + myTable.name());
System.out.println(sb.toString());
}
}
版权声明:本文为qq_38065439原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。