注解

基础语法

注解可以在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();
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值