注解
来源:互联网 发布:海之蓝淘宝旗舰店 编辑:程序博客网 时间:2024/06/13 01:47
基础语法
注解可以在package,class,method,filed上使用
//该注解表示方法被遗弃,会加一个横线在方法上。可以修饰方法,属性,类@Deprecated public static void test01() { System.out.println("这个方法被遗弃了,不推荐使用"); } public static void main(String[] args) { test01(); }
public class show { @myAnnotation(age=19, name="tom", id=100, schools={"实验小学","实验中学"}) public void test() { }}
//@Target(value=ElementType.METHOD)@Target(value={ElementType.METHOD,ElementType.TYPE})@Retention(RetentionPolicy.RUNTIME)public @interface myAnnotation { /* * @Target用于描述注解使用的范围 * package-->PACKAGE * 类,接口,枚举,注解-->TYPE * 类型成员(方法,构造方法,成员变量,枚举值)-->CONSTRUCTOR描述构造器,FIELD域,METHOD方法 * 方法参数和本地变量-->LOCAL VARIABLE局部变量,PARAMETER描述参数 */ /* * @Retention,描述注解的生命周期 * SOURCE-->在源文件中有效,即在源文件中保留 * CLASS-->在class文件中有效 * RUNTIME-->在运行的时候有效,运行时保留,可以被反射读取 */ //name() , age() 是参数名称 //默认值常用空字符串,0,-1 String name() default ""; int age() default 0; int id() default -1; String[] schools() default {"清华","北大"};}
@Target(value={ElementType.METHOD,ElementType.TYPE})@Retention(RetentionPolicy.RUNTIME)public @interface myAnnotation2 { //只有一个元素,通常叫value String value();}
public class show { //value="aaa"的省略写法 @myAnnotation2("aaa") public void test() { }}
反射读取注解
通过反射来读取注解,然后赋值
package com.bjsxt.test.annotation;@SxtTable("tb_student")public class SxtStudent {@SxtField(columnName="id",type="int",length=10)private int id;@SxtField(columnName="sname",type="varchar",length=10)private String studentName;@SxtField(columnName="age",type="int",length=3)private int age;public int getId() {return id;}public void setId(int id) {this.id = id;}public String getStudentName() {return studentName;}public void setStudentName(String studentName) {this.studentName = studentName;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}}
package com.bjsxt.test.annotation;import java.lang.annotation.ElementType;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;@Target(value={ElementType.TYPE})@Retention(RetentionPolicy.RUNTIME)public @interface SxtTable {String value();}package com.bjsxt.test.annotation;import java.lang.annotation.ElementType;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;@Target(value={ElementType.FIELD})@Retention(RetentionPolicy.RUNTIME)public @interface SxtField {String columnName();String type();int length();}
阅读全文