java annotation

3113 ワード

転載元:http://blog.csdn.net/lifetragedy/article/details/7394910#comments
この例は分かりました。

package com.shadow.test.annotation;

import com.shadow.test.annotation.ValueBind.fieldType;

public class Student {
	private String name = "";

	private int age = 0;

	private String studentId = "";
	
	@ValueBind(type = fieldType.STRING, value ="shadow")
	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 ="3051608")
	public void setStudentId(String studentId) {
		this.studentId = studentId;
	}

	public String getName() {
		return name;
	}
}


package com.shadow.test.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 {

	/**
	 *     
	 * @author shadow
	 *
	 */
	enum fieldType{STRING,INT};
	
	fieldType type();

    String value();
}

package com.shadow.test.annotation;

import java.lang.reflect.Method;

/**
 *          
 * 
 * @author shadow
 * 
 */
public class PersistObj {

	public static void main(String[] args) {
		try {
			Object c = Class.forName("com.shadow.test.annotation.Student")
					.newInstance();
			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(value));
					} else if (type.equals("STRING")) {
						methodArray[i].invoke(c, value);
					}
				}
			}

			Student annotaedStudent = (Student) c;

			System.out.println("studentId====" + annotaedStudent.getStudentId()
			+ "  studentnName====" + annotaedStudent.getName()
			+ "   student Age====" + annotaedStudent.getAge());

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}