java annotation

package annotation;

import java.io.Serializable;

import annotation.ValueBind.fieldType;

@SuppressWarnings("serial")
public class Student implements Serializable {

	private String name = "";

	public String getName() {
		return name;
	}

	@ValueBind(type = fieldType.STRING, value = "aa")
	public void setName(String name) {
		this.name = name;
	}

	public int getAge() {
		return age;
	}

	@ValueBind(type = fieldType.INT, value = "30")
	public void setAge(int age) {
		this.age = age;
	}

	public String getStudentId() {
		return studentId;
	}

	@ValueBind(type = fieldType.STRING, value = "101")
	public void setStudentId(String studentId) {
		this.studentId = studentId;
	}

	private int age = 0;
	private String studentId = "";
}

 

package annotation;

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

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface ValueBind {
	enum fieldType {
		STRING, INT
	};

	fieldType type();

	String value();
}

 

package annotation;

import java.lang.reflect.Method;

public class PersistStudent {
	public static void main(String[] args) throws Exception {
		Object c = Class.forName("annotation.Student").newInstance();
		try {
			Method[] methodArray = c.getClass().getDeclaredMethods();
			for (int i = 0; i < methodArray.length; i++) {
				if (methodArray[i].isAnnotationPresent(ValueBind.class)) {
					ValueBind annotation = methodArray[i].getAnnotation(ValueBind.class);
					String type = String.valueOf(annotation.type());
					String value = annotation.value();
					if (type.equals("INT")) {
						methodArray[i].invoke(c, new Integer[] { new Integer(value) });
					} else {
						methodArray[i].invoke(c, new String[] { value });
					}
				}
			}
			Student annotaedStudent = (Student) c;
			System.out.println("studentId====" + annotaedStudent.getStudentId() + "  studentnName====" + annotaedStudent.getName() + "   student Age====" + annotaedStudent.getAge());
		} catch (Exception e) {
			throw new Exception(e);
		}
	}
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值