java注解
1 Annotation
- 不是程序本身,可以对程序做出解释
- 可以被其他程序读取(编译器)
2 Annotation的格式
- @Override
3 Annotation可在哪里用
- 在类里面都可以用
public class Demo{
@Override
public String toString(){
return "";
}
}
public class Demo{
@Override//这里会报错
public String tostring(){
return "";
}
}
4 常见注解
- @Deprecated 不建议使用
- @Override 重写
- @SuppressWarnings抑制编译时的警告信息
SuppressWarnings(value = "all")
deprecation unchecked fallthrough path serial finally all 为参数
5 自定义注解
//@interface用于定义一个注解
@Targer{value=ElementType.Method }
public @interface MyAnnotation{
String studentName();
String studentName default ""; //用0或者空值表示默认值,-1表示不存在,之一一个参数通常定义为value
String[] schools() default {};
}
@Target用于描述注解的使用范围PACKAGE,TYPE,CIBSTRUCTOR,FIELD,METHOD,LOCAL VARIABLE,PARAMETER
@Retention表示在什么级别保存注释信息 SOURCE CLASS RUNTIME 注解的什么周期
6 注解的作用
- 使用注解完成类与表结构的映射关系(ORM 对象关系映射)
- 类与表结构对应
- 属性和字段对应
- 对象和记录对应
@Table = (table)
public class Student{
@Filed(columnName = "id",type = "int", length = 10)
private int id;
private String studentName;
private int age;
}
@Target(value = {ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface Table{
String value();
}
@Target(value = {ElementType.FIELD}) // 修饰属性
@Retention(RetentionPolicy.RUNTIME)
public @interface AFiled{
String columnName();
String type();
int length();
}
- 使用反射处理读取注解信息,模拟处理注解信息的流程
public class Demo{
pubolic static void main(String [] args){
try{
Class clz = class.forname("package.Student")
//获得类的所有注解
Annotation [] annotation = clz.getAnnotations;
Table st = (Table) clz.getAnnotation(Table.class);
//获得类的属性的注解
Filed f = clz.getDeclaredFiled("studentName");
AFiled afiled = (AFiled)f.getAnnotation(clz.class);
AFiled.columnName;
//根据获得的表面,就可以写SQL语句了
}
}
}
7 反射机制性能
- setAccessible
- 为true时反射对象在使用时取消Java语言的访问检查。职位false应该做java语言访问检查。
- 禁用安全检查,可以提高反射的运行速度。但安全性会降低
8 反射操作泛型
- java采用泛型擦除机制,java新增了ParameterizedType,几种类型来代表不能被归一到class类中的类型。但又于原始类相同的类
getGenericParameterTypes();//获得参数信息
getGenericReturnType();//获得返回信息
9 反射操作注解
//获得类注解
Annotation[] annotation = clz.getAnnotations();
Table st = (Table)clz.getAnnotation(Table.class);
Filed f= clz.getDeclaredFiled("studentName");
Filed1 filed1 = f.getAnnotation(Filed1.class);
网友评论