java annotationITeye - 凯发娱乐

java annotationITeye

2019-01-13 17:38:59 | 作者: 运乾 | 标签: 转载自,这个,比如 | 浏览: 2827

转载自: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();
版权声明
本文来源于网络,版权归原作者所有,其内容与观点不代表凯发娱乐立场。转载文章仅为传播更有价值的信息,如采编人员采编有误或者版权原因,请与我们联系,我们核实后立即修改或删除。

猜您喜欢的文章