利用反射机制读取注解(初步)

生来就可爱ヽ(ⅴ<●) 提交于 2020-02-26 08:00:14

初步实现注解的读取
读取注解=注解的建立+读取注解的实现
此处实现的是学生的相关注解的实现:
1.建立SxtStudent类,包含基本信息,并get,set;
2.建立SxtTable注解,包含一个值,记录表格的名字;
3.建立SxtField注解,包含SxtStudent类的基本属性的属性,记录表格基本信息的类型;
4.建立Demo类,进行测试,输出SxtStudent类的全部注解,输出SxtStudent的指定注解,输出SxtStudent类的所有属性和指定属性的注解

以下是代码:
1.SxtStudent

package com.sxt.reflectingtest;

@SxtTable("tb_student")
public class SxtStudent {
	
	@SxtField(columnName="id",type="int",length=10)
	private int id;
	@SxtField(columnName="age",type="int",length=3)
	private int age;
	@SxtField(columnName="sname",type="varchar",length=10)
	private String studentName;
	
	
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public String getStudentName() {
		return studentName;
	}
	public void setStudentName(String studentName) {
		this.studentName = studentName;
	}

}
2.SxtTable

package com.sxt.reflectingtest;

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

3.SxtField

package com.sxt.reflectingtest;

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

4.Demo

package com.sxt.reflectingtest;

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

public class Demo03 {   

	public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, SecurityException {
		
		Class clazz = Class.forName("com.sxt.reflectingtest.SxtStudent");
		
		//获得类的所有注解
		Annotation[] annotation = clazz.getAnnotations();
		for(Annotation a:annotation)
			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.length()+"--"+sxtField.type());
		
		
	}
}

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!