下面列出了java.lang.reflect.Field#isAnnotationPresent ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Override
protected boolean shouldCreatePersistentEntityFor(TypeInformation<?> type) {
boolean hasHashKey = false;
boolean hasRangeKey = false;
for (Method method : type.getType().getMethods()) {
if (method.isAnnotationPresent(DynamoDBHashKey.class))
hasHashKey = true;
if (method.isAnnotationPresent(DynamoDBRangeKey.class))
hasRangeKey = true;
}
for (Field field : type.getType().getFields()) {
if (field.isAnnotationPresent(DynamoDBHashKey.class))
hasHashKey = true;
if (field.isAnnotationPresent(DynamoDBRangeKey.class))
hasRangeKey = true;
}
return type.getType().isAnnotationPresent(DynamoDBTable.class) || (hasHashKey && hasRangeKey);
}
private static Entry extractField(Field field, Object owner){
field.setAccessible(true);
if (Modifier.isStatic(field.getModifiers())) {
return null;
}
if (field.isAnnotationPresent(MessageData.Ignore.class)) {
return null;
}
MessageData.FieldName fieldNameAnnotation = field.getAnnotation(MessageData.FieldName.class);
String fieldName = fieldNameAnnotation != null ? fieldNameAnnotation.value() : field.getName();
try {
Object fieldValue = field.get(owner);
if (fieldValue != null)
return new Entry(fieldName, serialize(fieldValue));
} catch (Exception e) {
//System.out.println(e.getClass().getSimpleName() + " " + e.getMessage());
}
return null;
}
private boolean hasValidationAnnotation(Field field) {
boolean hasAnnotation = field.isAnnotationPresent(NotNull.class)
|| field.isAnnotationPresent(NotBlank.class)
|| field.isAnnotationPresent(Max.class)
|| field.isAnnotationPresent(Min.class)
|| field.isAnnotationPresent(Pattern.class)
|| field.isAnnotationPresent(Size.class);
if (hasAnnotation) return true;
Class<?> targetClass = targetValidationClass(field);
if (!isValueClass(targetClass)) {
for (Field valueField : Classes.instanceFields(targetClass)) {
if (hasValidationAnnotation(valueField)) return true;
}
}
return false;
}
@Override
public void doWith(final Field field) throws IllegalArgumentException, IllegalAccessException {
if (!field.isAnnotationPresent(DataAccess.class)) {
return;
}
ReflectionUtils.makeAccessible(field);
final Type fieldGenericType = field.getGenericType();
// In this example, get actual "GenericDAO' type.
final Class<?> generic = field.getType();
final Class<?> classValue = field.getDeclaredAnnotation(DataAccess.class).entity();
if (genericTypeIsValid(classValue, fieldGenericType)) {
final String beanName = classValue.getSimpleName() + generic.getSimpleName();
final Object beanInstance = getBeanInstance(beanName, generic, classValue);
field.set(bean, beanInstance);
} else {
throw new IllegalArgumentException(ERROR_ENTITY_VALUE_NOT_SAME);
}
}
private Map<String, ColumnDefinition> getColumnDefinitionsFromFields(Object object) {
Class<?> clazz = object.getClass();
if (Objects.isNull(AnnotationUtils.findAnnotation(clazz, textTableClass))) {
return Collections.emptyMap();
}
Map<String, ColumnDefinition> columnDefinitions = new LinkedHashMap<>();
for (Field field : object.getClass().getDeclaredFields()) {
if (field.isAnnotationPresent(textColumnClass)) {
TextColumn textColumn = field.getAnnotation(textColumnClass);
String columnKey = StringUtils.defaultIfEmpty(textColumn.key(), field.getName());
columnDefinitions.put(columnKey, getColumnDefinition(textColumn, field));
}
}
return columnDefinitions;
}
private void injectActionPluginSender(String actionPlugin, ActionPluginListener pluginInstance) throws Exception {
if (pluginInstance == null) {
throw new IllegalArgumentException("pluginInstance must be not null");
}
Field[] fields = pluginInstance.getClass().getDeclaredFields();
Field sender = null;
for (Field field : fields) {
if (field.isAnnotationPresent(Sender.class) &&
field.getType().isAssignableFrom(ActionPluginSender.class)) {
sender = field;
break;
}
}
if (sender != null) {
ActionPluginSender standaloneSender = new StandaloneActionPluginSender(actions);
sender.setAccessible(true);
sender.set(pluginInstance, standaloneSender);
senders.put(actionPlugin, standaloneSender);
}
}
public Object $basic(String selector, Field field) throws Exception {
if (field.isAnnotationPresent(Text.class)) {// @Text
Text text = field.getAnnotation(Text.class);
String value = $text(selector, text.own());
return Conversion.getValue(field.getType(), value);
} else if (field.isAnnotationPresent(Image.class)) {// @Image
Image image = field.getAnnotation(Image.class);
String imageSrc = $image(selector, image.value());
/*String localPath = DownloadImage.download(image.download(), imageSrc);
if (StringUtils.isNotEmpty(localPath)) {
return localPath;
}*/
return imageSrc;
} else if (field.isAnnotationPresent(Href.class)) {// @Href
Href href = field.getAnnotation(Href.class);
String url = $href(selector, href.value());
return url;
} else if (field.isAnnotationPresent(Attr.class)) {// @Attr
Attr attr = field.getAnnotation(Attr.class);
String name = attr.value();
return Conversion.getValue(field.getType(), $attr(selector, name));
} else if (field.isAnnotationPresent(Html.class)) {// @Html
Html html = field.getAnnotation(Html.class);
return $html(selector, html.outer());
} else {// @Html
return $html(selector);
}
}
public static void mapDataType(XContentBuilder mappingBuilder, Field field) throws IOException {
if (!isValidStringFieldType(field)) {
throw new IllegalArgumentException(
String.format("field type[%s] is invalid type of string.", field.getType()));
}
if (field.isAnnotationPresent(StringField.class)) {
StringField stringField = field.getDeclaredAnnotation(StringField.class);
mapDataType(mappingBuilder, stringField);
return;
}
mappingBuilder.field("type", "keyword");
}
/**
* Generates an xml element from this pojo. Translating the fields like described
* in the class description.
* @param document The document in which the nodes should be.
* @param rootName This is to use another name for the root element than the
* simple class name.
* @param pojo The pojo to take the fields from.
* @param attributes The fields which should be used as attributes and not
* as elements.
* @return The create element representing the provided pojo.
* @throws ParserConfigurationException Might throw a ParserConfigurationException.
* @throws IllegalAccessException Might throw a IllegalAccessException.
* @throws InstantiationException Might throw a InstantiationException.
*/
public Element generateSimpleElement(final Document document, final String rootName,
final Object pojo, final List<String> attributes)
throws ParserConfigurationException,
IllegalAccessException, InstantiationException {
Element rootNode = document.createElementNS(getDefaultNamespace(), rootName);
List<Field> fields = getNonTransientSimpleFields(pojo.getClass());
for (Field field : fields) {
field.setAccessible(true);
String fieldName = field.getName();
if (field.get(pojo) != null) {
if (!attributes.contains(fieldName)) {
Element element = document.createElementNS(getDefaultNamespace(), getElementName(field));
// handle CDATAs
if (field.isAnnotationPresent(XmlValue.class)) {
CDATASection cdata = document.createCDATASection(field.get(pojo).toString());
element.appendChild(cdata);
}
else {
element.setTextContent(field.get(pojo).toString());
}
rootNode.appendChild(element);
}
else {
rootNode.setAttribute(getAttributeName(field), field.get(pojo).toString());
}
}
}
return rootNode;
}
/**
* Get annotated field. The field can be in parent field
*
* @param clazz clazz
* @param fieldName fieldName
* @param annotation annotation
* @return annotated field.
*/
public static Field getAnnotatedField(Class<?> clazz, String fieldName, Class<? extends Annotation> annotation) {
do {
Field[] fields = clazz.getDeclaredFields();
for(Field field : fields) {
if(Objects.equals(fieldName, field.getName()) && field.isAnnotationPresent(annotation)) {
return field;
}
}
clazz = clazz.getSuperclass();
}while (clazz != null);
return null;
}
/**
* 将bean按照@XStreamAlias标识的字符串内容生成以之为key的map对象
*
* @param bean 包含@XStreamAlias的xml bean对象
* @return map对象
*/
public static Map<String, String> xmlBean2Map(Object bean) {
Map<String, String> result = Maps.newHashMap();
List<Field> fields = new ArrayList<>(Arrays.asList(bean.getClass().getDeclaredFields()));
fields.addAll(Arrays.asList(bean.getClass().getSuperclass().getDeclaredFields()));
if(bean.getClass().getSuperclass().getSuperclass() == BaseWxPayRequest.class){
fields.addAll(Arrays.asList(BaseWxPayRequest.class.getDeclaredFields()));
}
if(bean.getClass().getSuperclass().getSuperclass() == BaseWxPayResult.class){
fields.addAll(Arrays.asList(BaseWxPayResult.class.getDeclaredFields()));
}
for (Field field : fields) {
try {
boolean isAccessible = field.isAccessible();
field.setAccessible(true);
if (field.get(bean) == null) {
field.setAccessible(isAccessible);
continue;
}
if (field.isAnnotationPresent(XStreamAlias.class)) {
result.put(field.getAnnotation(XStreamAlias.class).value(), field.get(bean).toString());
} else if (!Modifier.isStatic(field.getModifiers())) {
//忽略掉静态成员变量
result.put(field.getName(), field.get(bean).toString());
}
field.setAccessible(isAccessible);
} catch (SecurityException | IllegalArgumentException | IllegalAccessException e) {
log.error(e.getMessage(), e);
}
}
return result;
}
default void validate()
{
Class<? extends Object> klass = getClass();
while (klass != Object.class) {
for (Field field : klass.getDeclaredFields()) {
for (ValidationList.Validation validation : ValidationList.VALIDATIONS) {
Class<? extends Annotation> annotationClass = validation.annotationClass;
if (field.isAnnotationPresent(annotationClass)) {
Annotation annotation = field.getAnnotation(annotationClass);
Object value;
try {
field.setAccessible(true);
value = field.get(this);
}
catch (IllegalAccessException e) {
throw new RuntimeException(
String.format("Failed to get a value from field (%s)", field), e);
}
if (value == null) {
break;
}
if (!(value instanceof Number)) {
throw new IllegalArgumentException(
String.format("This field has (%s), but actual field is (%s)", annotation, value.getClass()));
}
if (!validation.isValid.apply(annotation, (Number) value)) {
throw new IllegalArgumentException(
String.format(validation.messageTemplate, field, value));
}
}
}
}
klass = klass.getSuperclass();
}
}
private static void readKeyNames() {
try {
Class[] healthStatsClasses = {
UidHealthStats.class,
PidHealthStats.class,
ProcessHealthStats.class,
PackageHealthStats.class,
ServiceHealthStats.class
};
Class annotationClass = Class.forName("android.os.health.HealthKeys$Constant");
for (Class clazz : healthStatsClasses) {
Field[] fields = clazz.getFields();
for (Field field : fields) {
if (field.isAnnotationPresent(annotationClass)) {
sKeyNames.put(field.getInt(null), field.getName());
}
}
}
return;
} catch (IllegalAccessException iae) {
SystemMetricsLogger.wtf(TAG, "Unable to read constant names", iae);
} catch (ClassNotFoundException cnfe) {
SystemMetricsLogger.wtf(TAG, "Unable to find constant annotation", cnfe);
}
// Mark as attempted and invalid
sKeyNames.put(-1, "Unable to read");
}
public boolean hasFieldAnnotation(Class<? extends Annotation> annotationType, Field field) {
return field.isAnnotationPresent(annotationType);
}
private static JSONObject dumpObject(Class<?> clazz, Stack<Class> hasDone) throws JSONException {
JSONObject jo = nj();
if (hasDone.contains(clazz)) {
jo.put("refer to", clazz.getName());
return jo;
}
hasDone.push(clazz);
logger.debug(String.format("dumping object: %s", clazz.getName()));
do {
Field[] fields = clazz.getDeclaredFields();
for (Field f : fields) {
if (f.isAnnotationPresent(APINoSee.class)) {
continue;
}
if (Modifier.isStatic(f.getModifiers())) {
continue;
}
Class ct = f.getType();
Type t = f.getGenericType();
if (ct.equals(clazz)) {
jo.put(f.getName(), "refer to self");
} else if (t instanceof ParameterizedType) {
ParameterizedType pt = (ParameterizedType) t;
if (Collection.class.isAssignableFrom(ct)) {
JSONArray arr = dumpCollection(pt, hasDone);
jo.put(f.getName(), arr);
} else if (Map.class.isAssignableFrom(ct)) {
Class<?> keyType = (Class<?>) pt.getActualTypeArguments()[0];
if (!String.class.isAssignableFrom(keyType)) {
throw new IllegalArgumentException(String.format(
"Field[%s] of class[%s] is type of Map, but type[%s] of its key element is not String, unable to dump", f.getName(),
clazz.getName(), keyType));
}
JSONObject mj = dumpMap(pt, hasDone);
jo.put(f.getName(), mj);
} else {
throw new IllegalArgumentException(String.format(
"Field[%s] of class[%s] is type of java generic type[%s], but it's not Collection or Map, unable to dump", f.getName(),
clazz.getName(), pt.getRawType()));
}
} else {
if (isPrimitiveType(ct)) {
jo.put(f.getName(), populateTemplateString(f));
} else if (Collection.class.isAssignableFrom(ct)) {
logger.warn(String.format(
"Field[%s] of class[%s] is type of Collection, unable to dump it because it doesn't have java generic type information",
f.getName(), clazz.getName()));
jo.put(f.getName(), dumpObject(ArrayList.class, hasDone));
} else if (Map.class.isAssignableFrom(ct)) {
logger.warn(String.format(
"Field[%s] of class[%s] is type of Map, unable to dump it because it doesn't have java generic type information", f.getName(),
clazz.getName()));
jo.put(f.getName(), dumpObject(HashMap.class, hasDone));
} else {
logger.debug(String.format("dumping %s, %s", f.getName(), ct.getName()));
JSONObject oj = dumpObject(ct, hasDone);
jo.put(f.getName(), oj);
}
}
}
clazz = clazz.getSuperclass();
} while (clazz != null && clazz != Object.class);
hasDone.pop();
return jo;
}
private String mongoField(Field field) {
if (field.isAnnotationPresent(Id.class)) return "_id";
return field.getDeclaredAnnotation(core.framework.mongo.Field.class).name();
}
public LayerConfigPanel createPanel(Project project, SourceGroup sourceGroup, String _package) {
if (panel == null) {
if (isValid()) {
try {
panel = getTechnology().panel().newInstance();
} catch (InstantiationException | IllegalAccessException ex) {
Exceptions.printStackTrace(ex);
}
} else {
panel = new DefaultConfigPanel();
}
Class<LayerConfigData> configDataClass = panel.getConfigDataClass();
panel.setConfigData(PreferenceUtils.get(project, configDataClass));
Map<Class<? extends LayerConfigPanel>, LayerConfigPanel> siblingData = new HashMap<>();
Map<Class<? extends LayerConfigPanel>, LayerConfigPanel> cacheSiblingData = new HashMap<>();
for(TechContext siblingContext : getSiblingTechContext()){
LayerConfigPanel siblingPanel = siblingContext.createPanel(project, sourceGroup, _package);
siblingData.put(siblingPanel.getClass(), siblingPanel);
}
cacheSiblingData.putAll(siblingData);
cacheSiblingData.put(panel.getClass(), panel);
Iterator<Entry<Class<? extends LayerConfigPanel>, LayerConfigPanel>> iterator = siblingData.entrySet().iterator();
while(iterator.hasNext()){
Entry<Class<? extends LayerConfigPanel>, LayerConfigPanel> entry = iterator.next();
LayerConfigPanel instance = entry.getValue();
List<Field> fields = Arrays.asList(instance.getClass().getDeclaredFields());
for (Field field : fields) {
if (field.isAnnotationPresent(ConfigData.class)) {
field.setAccessible(true);
try {
if (LayerConfigPanel.class.isAssignableFrom(field.getType())) {
field.set(instance, cacheSiblingData.get(field.getType()));
}
} catch (IllegalArgumentException | IllegalAccessException e) {
e.printStackTrace();
}
}
}
instance.init(_package, project, sourceGroup);
instance.read();
}
if (parentTechContext == null) { //if sibling context then first inject field and then init
panel.init(_package, project, sourceGroup);
panel.read();
}
}
return panel;
}
private static boolean isChoice(Field field) {
return field.isAnnotationPresent(Choice.class);
}
private boolean isUnique(Field field) {
return field.isAnnotationPresent(UNIQUE_CLASS);
}
public static boolean hasAnnotation(Field field, Class<? extends Annotation> clazz) {
return field.isAnnotationPresent(clazz);
}