Java Annotation 刷课笔记(一)
1.什么是注解?
1.1.Annotation是从JDK5.0引入的新技术
1.2.Annotation的作用:
- 不是程序本身,可以对程序作出解释(这一点,和注释没什么区别)
- 可以被其他程序(比如编译器)读取,注解信息处理流程,是注解和注解的重大区别,如果没有注解信息的处理流程,则注解毫无意义
1.3.内置注解
@Override 重载
@Deprecated 不建议使用
@SupressWarning 去除警告信息
2.自定义注解
2.1.自定义注解的前提是注解上要加入两个元注解
2.1.1.Target 注解目标是谁
package 包
type 类,接口,枚举,Annotation
constructor 构造器
field 描述域
method 描述方法
local_variable 局部变量
2.1.2 Retention 需要在什么级别保存注解信息,用于描述注释的声明周期(是CLASS,SOURCE还是RUNTIME)
source 在源文件中保留
class 在class文件中保留
runtime 在运行时可以被反射读取(这个用的比较多)
2.1.3 可以写类似方法的参数
String stu() default "";
3.利用反射机制读取注解信息
示例:使用反射写一个程序来创建tb_student表
studnet类
package littlepage.annotation.demo01; @AnnoTable("tb_student") public class Student { @AnnoField(columnName = "id",type = "int",length = 10) private int id; @AnnoField(columnName = "name",type = "varchar",length = 255) private String name; @AnnoField(columnName = "field",type = "varchar",length = 10) private int age; }
AnnoTable Annotation
package littlepage.annotation.demo01; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) public @interface AnnoTable { String value(); }
AnnoField Annotation
package littlepage.annotation.demo01; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) public @interface AnnoField { String columnName(); String type(); int length(); }
转换类
package littlepage.annotation.demo01; import java.lang.annotation.Annotation; import java.lang.reflect.Field; public class Demo01 { public static void toSQL(Class<?> clazz) { //拿到类名上的属性值 AnnoTable table = (AnnoTable) clazz.getAnnotation(AnnoTable.class); String tableName = table.value(); //拼SQL StringBuilder sb = new StringBuilder(); sb.append("create table ").append(tableName).append("(\n"); //拿到各个Field Field[] fields = clazz.getDeclaredFields(); String fieldString; for (Field field : fields) { Annotation[] annotations=field.getAnnotations(); for (Annotation annotation:annotations) { String annotationString=annotation.toString(); String columnName=annotationString.substring(annotationString.indexOf("columnName=")+11,annotationString.indexOf(", type")); String typeName=annotationString.substring(annotationString.indexOf("type=")+5,annotationString.indexOf(", length")); String length=annotationString.substring(annotationString.indexOf("length=")+7,annotationString.indexOf(")")); sb.append(columnName+" "+typeName+"("+length+"),\n"); } } sb.replace(sb.length()-1,sb.length(),"\n);"); System.out.println(sb); } public static void main(String[] args) { toSQL(Student.class); } }