java注解 (二)

2014-11-24 08:12:16 · 作者: · 浏览: 1
annoField.fieldValue());
}
}
} catch (SecurityException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}

/**
* 解释注解中的值,并且赋值给相关属性或者方法
*/
public void testDoIt() {
try {
AnnotationUser user = new AnnotationUser();
Field field = user.getClass().getDeclaredField("userField");
if (field.isAnnotationPresent(AnnotationField.class)) {
AnnotationField annoField = field.getAnnotation(AnnotationField.class);

// getDeclaredMethod()返回一个 Method 对象,该对象反映此 Class
// 对象所表示的类或接口的指定已声明方法。name 参数是一个
// String,它指定所需方法的简称,parameterTypes 参数是 Class 对象的一个数组
// Method doIt = user.getClass().getDeclaredMethod("doIt");

// 属性必须要由set 或者get 方法,才能调用invoke方法
PropertyDescriptor pd = new PropertyDescriptor(field.getName(), AnnotationUser.class);
Method doIt = pd.getWriteMethod();

if (null != doIt) {
String value = annoField.fieldValue();
doIt.invoke(user, value);
}
}
user.doIt();
} catch (Exception e) {
e.printStackTrace();
}
}

}


摘自 yanbin_new