自定义注解

一、内置注解

1)@Override:重写方法

2)@Deprecated:遗弃的(不推荐使用)

3)@SuppressWarnings:压制编译时的警告信息

都定义在Java的lang包中。

二、自定义注解(在一个包上右击-->new-->javaclass-->下翻找到annotation-->输入name)

1、自定义注解

1)定义类的注解

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

 2)定义属性的注解

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 len();
}

 2、使用自定义注解

package com.bjsxt.test.annotation;
@SxtTable("tb-table")
public class SxtStudent {
    @SxtField(columnName ="id",type="int",len=10 )
    private int id;
    @SxtField(columnName ="name",type="String",len=10 )
    private String name;
    @SxtField(columnName ="age",type="int",len=3 )
    private int age;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

 3、得到注解

package com.bjsxt.test.annotation;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;

public class Demon03 {
    public static void main(String[] args) {
        try {
            Class clazz=Class.forName("com.bjsxt.test.annotation.SxtStudent");
            //获得该类的所有注解
            Annotation[] annotations=clazz.getAnnotations();
            for( Annotation a:annotations){
                System.out.println(a);
            }
            //获得类的指定的注解
            SxtTable st=(SxtTable) clazz.getAnnotation(SxtTable.class);
            System.out.println(st.value());
            //获得类的属性的注解
            Field f=clazz.getDeclaredField("name");
            SxtField sxtfield=f.getAnnotation(SxtField.class);
            System.out.println(sxtfield.columnName());


            //根据获得的类名、字段的信息,拼出DDL语句,使用JDBC执行这个SQL,在数据库中生成相对应的表
        } catch (ClassNotFoundException | NoSuchFieldException e) {
            e.printStackTrace();
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值