java注解和反射

2019-07-24  本文已影响0人  吃块西瓜写代码

java注解

1 Annotation

2 Annotation的格式

3 Annotation可在哪里用

public class Demo{
     @Override
     public String toString(){ 
          return "";
    }
}
public class Demo{
     @Override//这里会报错
     public String tostring(){ 
          return "";
    }
}

4 常见注解

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 注解的作用

@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 反射机制性能

8 反射操作泛型

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);


上一篇 下一篇

猜你喜欢

热点阅读