Java注解

 

 

 

 

 

 

 

 

 

 

 

 

前面都是抄的别人的,发点自己的东西

package 注解.反射读取;

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(value = RetentionPolicy.RUNTIME)
public @interface SxtTable
{
        String value();
}

  

package 注解.反射读取;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

//用来说明SXtStudent 里面的属性特性

@Target(value = ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface SxtFiled
{
    String columnName();
    String type();
   int length();
}
package 注解.反射读取;

@SxtTable("tb_table")

public class SxtStudent
{
    @SxtFiled(columnName = "id",type="int",length = 10)
    private int id;
    //对属性做了说明,

    @SxtFiled(columnName = "sname",type="varchar",length = 10)
    private  String StudentName;

    @SxtFiled(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) {
        StudentName = studentName;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}
package 注解.反射读取;

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

//反射读取ANN
public class DEMO
{
    public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException
    {
      Class Clazz= Class.forName("注解.反射读取.SxtStudent");//包含对应类的全部信息 包含注解

//        Annotation annot[]=Clazz.getAnnotations();//获取注解
//        for(Annotation a:annot)
//        {
//            System.out.println(a);
//        }

        
        //直接获得特定的注解
//        SxtTable st= (SxtTable) Clazz.getAnnotation(SxtTable.class);
//        System.out.println(st);


        //获得对应类的属性的注解
        Field f=Clazz.getDeclaredField("StudentName");
        System.out.println(f);
        SxtFiled sxtf=f.getAnnotation(SxtFiled.class);
        System.out.println(sxtf);
        System.out.println(sxtf.columnName());
        System.out.println(sxtf.length());
        System.out.println(sxtf.type());
    }
}

  

posted @ 2020-06-19 14:34  Loving-Q  阅读(591)  评论(0编辑  收藏  举报