一直都想了解一下注解,下面是自己学到的一点东西。
1.分类
- 内置注解(@Override,@Deprecated,@SuppressWarnings),源码上很清楚的备注了各自的作用。
- 元注解(@Retention,@Target...),还是看源码备注。
- 自定义注解 。
2.应用
1.注解(annotation)作为注释用(comment),很明显这不是主要作用。
2.被其他程序调用(如编译器)。
3.实例
package com.test.annotation;
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 Table {
String value();
}
package com.test.annotation;
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.FIELD)
public @interface Column {
String colName();
String type();
int length();
// 不传值取默认值
boolean isNull() default true;
}
package com.test.annotation;
@Table("student")
public class Student {
@Column(colName = "id", type = "bigint", length = 20, isNull = true)
private Long id;
@Column(colName = "name", type = "varchar", length = 20, isNull = false)
private String name;
@Column(colName = "age", type = "int", length = 3)
private int age;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
import com.test.annotation.Column;
import com.test.annotation.Table;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
public class Main {
public static void main(String[] args) {
try {
String sql;
Class clazz = Class.forName("com.test.annotation.Student");
// 读取类的注解
for (Annotation annotation : clazz.getAnnotations()) {
System.out.println(annotation);
}
// 获取类的指定注解
Table table = (Table) clazz.getAnnotation(Table.class);
//System.out.println(table.value());
sql = "create table " + table.value() + " ( " +"\n";
// 获取类的属性的注解
Field id = clazz.getDeclaredField("id");
Column idAnnotation = id.getAnnotation(Column.class);
System.out.println(idAnnotation.colName());
for (Field field : clazz.getDeclaredFields()) {
Column col = field.getAnnotation(Column.class);
sql = sql + " " + col.colName() + " " + col.type() + "(" + col.length() +") " + (col.isNull() ? "default null" : "not null") +",\n";
}
sql.lastIndexOf(',');
sql = sql.substring(0, sql.length() - 2) + "\n);";
System.out.println(sql);
} catch (Exception e) {
}
}
}
/*运行结果:
@com.test.annotation.Table(value=student)
id
create table student (
id bigint(20) default null,
name varchar(20) not null,
age int(3) default null
);*/
通过反射读取Student类上的@Table和@Column注解生成SQL语句。