Java基础---反射得到注解(2)

     使用Java反射机制,在运行时你可以访问到Java类中所附属的一些注解。下面是本文所涵盖的主题列表:

  1. What are Java Annotations? (什么是Java注解)
  2. Class Annotations (类注解)
  3. Method Annotations (方法注解)
  4. Parameter Annotations (参数注解)
  5. Field Annotations (字段注解)

         @Override对父类的方法重写:

        @Deprecated过时的,废弃的:

        @SuppressWarning 镇压报警信息

 

Class类的方法

--用反射得到注解相关信息

package com.bjsxt.test;


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();
}
注解属性的类
package com.bjsxt.test;

/**
 * 注解类
 */
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;
@SxtTable("tb_student")
public class SxtStudent {
    @SxtField(columnName="id",type="int",length=10)
    private int id;
    @SxtField(columnName="studentName",type="varchar",length=10)
    private String studentName;
    @SxtField(columnName="age",type="int",length=10)
    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;

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

/**
 * 通过反射获取注解信息
 * @author
 *
 */
public class Demo1 {
    public static void main(String[] args) {
        try {
            Class clazz = Class.forName("com.bjsxt.test.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("studentName");
            SxtField sxtField = f.getAnnotation(SxtField.class);
            System.out.println(sxtField.columnName()+"--"+sxtField.type()+"--"+sxtField.length());
            
            //根据获得的表名、字段的信息,拼出DDL语句,然后,使用JDBC执行这个SQL,在数据库中生成相关的表
            
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}


@com.bjsxt.test.SxtTable(value=tb_student)
tb_student
studentName--varchar--10
测试用

 

posted @ 2017-07-14 08:51  周无极  阅读(239)  评论(0编辑  收藏  举报