从JDK5加入注解和反射后,java的编程方式具有了动态性,有了一点python语言那种编码的快感,来一个小Demo
MyAnnotationClass.java
package spring_annotation.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotationClass {
// String name();
String name() default "";
// String type();
String type() default "";
}
MyAnnotationFiled.java
package spring_annotation.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 MyAnnotationFiled {
String value() default "";
String type() default "";
int length() default 0;
}
TestObject.java
package spring_annotation.pojo;
import lombok.*;
import lombok.experimental.Accessors;
import spring_annotation.annotation.MyAnnotationClass;
import spring_annotation.annotation.MyAnnotationFiled;
@Data
@AllArgsConstructor
@NoArgsConstructor
@Accessors(chain = true)
@Builder
@MyAnnotationClass(name = "t_object", type = "innodb")
public class TestObject {
@MyAnnotationFiled(value = "id", type = "int", length = 10)
private Integer id;
@MyAnnotationFiled(value = "name", type = "varchar", length = 20)
private String name;
@MyAnnotationFiled(value = "age", type = "int", length = 10)
private Integer age;
}
Annotation.java
import org.junit.jupiter.api.Test;
import spring_annotation.annotation.MyAnnotationClass;
import spring_annotation.annotation.MyAnnotationFiled;
import spring_annotation.pojo.TestObject;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
public class AnnotationTest {
@Test
public void test01() throws ClassNotFoundException, IllegalAccessException,
InstantiationException, NoSuchFieldException {
String path = "spring_annotation.pojo.TestObject";
Class clazz = Class.forName(path);
TestObject testObject = (TestObject) clazz.newInstance();
System.out.println(testObject.setId(1).setName("zzz").setAge(20));
Annotation[] declaredAnnotations = clazz.getDeclaredAnnotations();
for (Annotation declaredAnnotation : declaredAnnotations) {
System.out.println(declaredAnnotation);
}
MyAnnotationClass annotation = (MyAnnotationClass) clazz.getAnnotation(MyAnnotationClass.class);
System.out.println(annotation.name()+"--->"+annotation.type());
Field f = clazz.getDeclaredField("id");
MyAnnotationFiled af = f.getAnnotation(MyAnnotationFiled.class);
System.out.println(af.value()+"--->"+af.type()+"--->"+af.length());
}
}
网友评论