修改带有将带有annotation的变量
需要setAccessible(true)后才能修改变量的值
可以修改private、final、static
public BaseCrawlerRequest convertToCrawlerBean(BaseCrawlerRequest bean) throws Exception {
Field nameField = getNameField(bean.getClass());
nameField.setAccessible(true);
String nameValue = (String) nameField.get(bean);
if (StringUtils.isNotEmpty(this.type)) {
if (StringUtils.isNotEmpty(nameValue)) {
nameField.set(bean, this.type + EnumConstant.CONNECT_FIELD + nameValue);
} else {
nameField.set(bean, this.type);
}
}
return this;
}
找到带有@NameField的Field
private Field getNameField(Class clazz) throws Exception {
Field[] fields = clazz.getDeclaredFields();
for (Field field : fields) {
for (Annotation ann : field.getDeclaredAnnotations()) {
if (ann.annotationType() == NameField.class) {
return field;
}
}
}
throw new Exception("BaseCrawlerRequest getgetNameField failed. no annotation @NameField in " + clazz.getName());
}