什么是注解:
JDk1.5新增技术,注解。很多的框架为了简化代码,都会提供一下注解,可以理解为插件,是代码级别的 插件。在类的方法上写:@XXX,就是在代码上插入了一个插件。
注解不会也不能影响代码的实际逻辑,仅仅是起到辅助的作用。
注解分类:
内置注解,(元注解jdk自带的注解)
自定义注解:(Spring 框架注解)
Object类中有哪些方法:
notify(): 唤醒当前的线程。
toString():输出当前类的信息。
失信自定义注解类:
元注解的作用就是负责注解其他的注解。Java5.0定义了4个标准的mata-annotation类型,他们被用来提供对其他annotation类型作说明,Java5.0定义的元注解:
@Target:
@Target:说明会了Annotation所修饰的对象的范围,Annotation可被用于package,type(接口,类,枚举Annotation类型),类型成员(方法,构造方法,构造函数,成员变量,枚举值),方法参数和本地变量(循环变量,catch参数)。在Annotation类型的声明中使用了target可更加清晰起修饰的目标。
1.CONSTRUCTOR:用于描述构造起。
2。FIFLD:用于描述数据域,
3。LOCAL_VARIABLE:用于描述局部变量。
4。METHOD:用于描述方法。
5:PACKAGE:用于描述包。
6:PARAMETER:用于描述参数。
7。TYPE:用于描述类,接口,(包含注解类型),或者enum声明。
2.@Retention :
表示需要在什么级别保存该注释信息,用于描述注解的声明周期。(即:被描述的注解在什么范围内有效)
3.@Documented:
4.@Inherited:
自定义注解类:
/**
* 表示该类是一个自定义注解类
*/
@Target(ElementType.METHOD)//表示该主机的使用范围,methof表示只能在方法上面使用。
@Retention(RetentionPolicy.RUNTIME)//表示该注解的生命周期。
public @interface AutoDemo02 {
int beaId () default 0;
String ClassName () default "";
String [] array();//没加上defaul表示该参数是必填的 。
}
利用java反射和注解实现sq的拼接:
public class AnnotationMain {
public static void main(String[] args) throws Exception{
StringBuffer sb = new StringBuffer();//拼接的参数
Class<?> forName = Class.forName("com.itmayiedu.day01.StudentsEntity");
//获取类上边的注解
Table table = forName.getDeclaredAnnotation(Table.class);
sb.append("select");
System.out.println(table.value());
//获取属性上面的注解 先获取所有的属性。
Field[] declaredFields = forName.getDeclaredFields();
for (Field field:declaredFields) {
Perporty perporty = field.getDeclaredAnnotation(Perporty.class);
System.out.println(perporty.name());
sb.append(" "+perporty.name()+", ");
}
sb.append(" from " +table.value());
sb.replace(sb.lastIndexOf(","),sb.lastIndexOf(",")+1," ");
System.out.println(sb.toString());
}
}
常见Table类:
/**
* 表名映射类
*/
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface Table {
String value();
}
编写属性映射:
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Perporty {
String name();
int length() default 0;
}
编写实体映射类:
@Table("student")//" "引号里面表示数据库的表的名字
public class StudentsEntity {
@Perporty(name="student_id",length = 10)//name的值表示数据库的字段
private String studentName;
@Perporty(name = "student_name")//name的值表示数据库的字段
private String studentId;
@Perporty(name="student_age")//name的值表示数据库的字段
private String studentAge;
@Perporty(name = "student_weigth")
private String studetWeigth;
}