通过反射读取自定义注解

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/fhm6100411074/article/details/79779589

一、自定义注解 Table

package com.sh.fhm.MavenTest.reflect;

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 Table {
	String value();

}

二、自定义注解 Record

package com.sh.fhm.MavenTest.reflect;

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(value = RetentionPolicy.RUNTIME)
public @interface Record {
	String name();
	String type();
	int length();

}

三、使用注解:

package com.sh.fhm.MavenTest.reflect;


@Table(value = "tb_student")
public class Student {
	@Record(name = "name", type = "varchar", length = 50)
	private String name = "周杰伦";
	@Record(name = "age", type = "int", length = 10)
	private Integer age = 28;

}

四、测试类:

package com.sh.fhm.MavenTest.reflect;

import java.lang.reflect.Field;

public class ReflectTest {
	public static void main(String[] args) throws Exception {
		Class<?> clz = Class.forName("com.sh.fhm.MavenTest.reflect.Student");
		/*
		 * public <A extends Annotation> A getAnnotation(Class<A> annotationClass(注解类型))
		 * 通过反射获取注解类型
		 */
	     Table table = clz.getAnnotation(Table.class);
	     System.out.println(table.value());
		
	     Field field =  clz.getDeclaredField("name");
	     Record record = field.getAnnotation(Record.class);
	     System.out.println(record.name() + " " + record.type() + " " + record.length());
	     
	     field = clz.getDeclaredField("age");
	     record = field.getAnnotation(Record.class);
	     System.out.println(record.name() + " " + record.type() + " " + record.length());
	}
}



猜你喜欢

转载自blog.csdn.net/fhm6100411074/article/details/79779589