*自定义注解:1.使用@interface自定义注解时,自动继承了java.lang.annotation.Annotation接口
* 2.格式:public @interface 注解名{定义体}
* 3.其中的每一个方法实际上是声明了一个配置参数:
* a.方法的名称就是参数的名称.
* b.返回值类型就是参数的类型(返回值类型只能是基本类型、class、string、enum).
* c.可以通过default来声明参数的默认值
* d.如果只有一个参数成员,一般参数名为value
* 元注解:作用是负责注解其他注解,java定义了4个标准的meta-annotation类型,
* 它们被用来提供对其他annotation类型作说明:
* @Target 用于描述注解的使用范围,值有PACKAGE(包)、TYPE(类、接口、枚举、Annotation类型)、
* CONSTRUCTOR(描述构造器)、FIELD(属性)、METHOD(方法)、LOCAL VARLEU(局部变量)、
* PARAMETER(参数)
* @Retention 描述注解的生命周期,值有SOURCE(在源文件中有效)、CLASS(在源文件中有效)、
* RUNTIME(运行时有效,可以被反射机制读取)
* @Documented
* @Inherited
* 注解只是写出来没多大用处,还要写解析,那才是完整的。
自己写注解来实现类与表结构的映射关系
首先有个类:
public class Student {
private int id;
private String snume;
private int age;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getSnume() {
return snume;
}
public void setSnume(String snume) {
this.snume = snume;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Student(int id, String snume, int age) {
this.id = id;
this.snume = snume;
this.age = age;
}
public Student(){
}
}
然后写一个和数据库表名映射的注解:
@Target(value ={ElementType.TYPE} )
@Retention(RetentionPolicy.RUNTIME)
public @interface StudentTable {
String value();
}
写一个和数据库表信息映射的注解,一般有长度、类型、列名,还有其他,我们就要这三个来写例子:
@Target(value ={ElementType.FIELD} )
@Retention(RetentionPolicy.RUNTIME)
public @interface StudentField {
String columnName();
String type();
int length();
}
然后在Student类中加上注解:
@StudentTable("tb_student")//tb_student是数据库中表名
public class Student {
@StudentField(columnName = "id",type = "int",length = 10)
private int id;
@StudentField(columnName = "sname",type = "varchar",length = 10)
private String snume;
@StudentField(columnName = "age",type = "int",length = 3)
private int age;
......后面省略
当然有解析才是完整的,可以通过反射解析注解。