jexhuang
8/30/2018 - 6:55 AM

Reflection

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

@Retention(RetentionPolicy.RUNTIME)
@Target(value = { ElementType.FIELD, ElementType.METHOD })
public @interface FieldName {

	String name();
}

public class Member {

	@FieldName(name = "n")
	String name;
	@FieldName(name = "a")
	String age;

	@FieldName(name = "getn")
	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	@FieldName(name = "geta")
	public String getAge() {
		return age;
	}

	public void setAge(String age) {
		this.age = age;
	}

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

public class Main {

	public static void main(String[] args) throws Exception {
		Class clz = Member.class;
		System.out.println(clz.getName());
		Field[] fields = clz.getDeclaredFields();
		for (Field field : fields) {
			if (field.isAnnotationPresent(FieldName.class)) {
				System.out.println(field.getName() + " has annotation");
				System.out.println(field.getAnnotation(FieldName.class).name());
			}
		}
		// Annotation a = clz.getAnnotation(FieldName.class);
		// System.out.println(a.getClass().getName());
		Method method = clz.getMethod("getName");
		if (method.isAnnotationPresent(FieldName.class)) {
			System.out.println("@FieldName is found.");

			FieldName debug = method.getAnnotation(FieldName.class);
			System.out.println("name = " + debug.name());
		} else {
			System.out.println("@FieldName is not found.");
		}

		Annotation[] annotations = method.getAnnotations();
		for (Annotation annotation : annotations) {
			System.out.println(annotation.annotationType().getName());
		}
	}

}