下面列出了java.lang.reflect.Field#getAnnotationsByType ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public static <T> String getFieldName(EntityGetterMethod<T, Object> expression) {
if (expression == null)
throw new IllegalArgumentException("Expression should not be null");
try {
Method method = expression.getClass().getDeclaredMethod("writeReplace");
method.setAccessible(Boolean.TRUE);
SerializedLambda serializedLambda = (SerializedLambda)method.invoke(expression);
String fieldName = StringUtils.resolveFieldName(serializedLambda.getImplMethodName());
String className = serializedLambda.getImplClass().replace("/", ".");
Field field = ReflectionUtils.findField(Class.forName(className), fieldName);
String columnName = field.getName();
TableField[] tableField = field.getAnnotationsByType(TableField.class);
if (null != tableField && tableField.length == 1) {
if (!StringUtils.isEmpty(tableField[0].value())) {
columnName = tableField[0].value();
}
}
String ret = StringUtils.camelToUnderline(columnName);
return ret;
} catch (ReflectiveOperationException e) {
throw new RuntimeException("This will never happen!", e);
}
}
private void buildMappings() {
Field[] fields = clazz.getDeclaredFields();
for (Field field : fields) {
Attribute[] attributes = field.getAnnotationsByType(Attribute.class);
PartitionKey[] partitionKey = field.getAnnotationsByType(PartitionKey.class);
SortKey[] sortKey = field.getAnnotationsByType(SortKey.class);
if (attributes.length > 0) {
fieldNames.add(field.getName());
}
if (partitionKey.length > 0) {
fieldNames.add(field.getName());
padding.put(field.getName(), partitionKey[0].padding());
}
if (sortKey.length > 0) {
fieldNames.add(field.getName());
}
}
}
private void handleFieldMapView(Class<?> entityClass, Map<String, Meta> result, String[] groups, Field field) {
final MapView[] views = field.getAnnotationsByType(MapView.class);
for (MapView view : views) {
String[] viewGroups = view.groups();
if (viewGroups.length == 0) {
viewGroups = groups.clone();
}
for (String group : viewGroups) {
if (predicate.test(group)) {
final String entityClassName = entityClass.getName();
final String format = format("%s 类的属性 %s 上使用注解@MapView,注解的name属性不能为空", entityClassName, field.getName());
final io.gd.generator.annotation.Field viewField = view.field();
final String label = handleFieldLabel(field, viewField.label(),
format("%s 类中的字段 %s 上使用@MapView时,@Field的label属性为空", entityClass.getName(), field.getName()));
doHandleMapView(entityClass, result, view, group, entityClassName, format, field.getType(), label, viewField.order());
}
}
}
}
/**
* Updates the reflected reference to the {@link Field} this object is defined in.
* <p>
* This is needed to work around type erasure.
*/
void bind(Field containingField) {
Preconditions.checkArgument(
Flag.class.isAssignableFrom(containingField.getType()),
"Passed Field is not a Flag<?>.");
FlagInfo[] annotations = containingField.getAnnotationsByType(FlagInfo.class);
Preconditions.checkArgument(
annotations.length == 1,
"FlagField containing field must contain exactly one @FlagInfo annotation.");
FlagInfo annotation = annotations[0];
this.name = Strings.isNullOrEmpty(annotation.name())
? containingField.getName()
: annotation.name();
this.altName = annotation.altName();
this.help = annotation.help();
this.containingField = containingField;
// Extract the Class<X> or ParametrizedType<X> from Flag<X>
this.containingFieldType = ((ParameterizedType) containingField.getGenericType())
.getActualTypeArguments()[0];
this.unusedMarker = containingField.isAnnotationPresent(FlagzUnused.class);
}
private static List<Map<String, Object>> processParameters(Field field) {
List<Map<String, Object>> parametersOutput = new ArrayList<>();
ConfigurationParameter[] parameters = field.getAnnotationsByType(ConfigurationParameter.class);
for (ConfigurationParameter param : parameters) {
if (ExternalResourceFactory.PARAM_RESOURCE_NAME.equals(param.name())) {
continue;
}
Map<String, Object> parameterOutput = new HashMap<>();
parameterOutput.put("name", param.name());
parameterOutput.put("defaultValue", stringArrayToString(param.defaultValue()));
parameterOutput.put("type", "parameter");
parametersOutput.add(parameterOutput);
}
return parametersOutput;
}
private static List<Map<String, Object>> processResources(Field field) {
List<Map<String, Object>> resourcesOutput = new ArrayList<>();
ExternalResource[] resources = field.getAnnotationsByType(ExternalResource.class);
for (ExternalResource resource : resources) {
Map<String, Object> resourceOutput = new HashMap<>();
resourceOutput.put("key", resource.key());
resourceOutput.put("class", field.getType().getName());
resourceOutput.put("type", "resource");
resourceOutput.put("parameters", getParameters(field.getType()));
resourcesOutput.add(resourceOutput);
}
return resourcesOutput;
}
/** Checks if this instance can be merged with another
*
* Other must have all the fields that this instance has, and
* the fields that are annotated as MergeByAssertEquals must contain the same value
*
* @param other metric that will be merged into this one.
* @return true if the other metric can be merged into this one.
*/
public boolean canMerge(final MergeableMetricBase other) {
try {
for (final Field field : this.getClass().getDeclaredFields()) {
if (field.isSynthetic()) continue;
//try to get field from other, will throw exception if other instance doesn't have the
field.get(other);
final Annotation[] equalAnnotations = field.getAnnotationsByType(MergeByAssertEquals.class);
if (equalAnnotations.length != 0) {
if (field.get(this) == null) return true;
if (field.get(other) == null) return true;
if (!field.get(this).equals(field.get(other))) return false;
}
}
} catch (final Exception e) {
return false;
}
return true;
}
boolean hasJunitTimeout(Description description) {
// Do not do apply the default timeout if the test has its own @Test(timeout).
Test testAnnotation = description.getAnnotation(Test.class);
if (testAnnotation != null && testAnnotation.timeout() > 0) {
return true;
}
// Do not do apply the default timeout if the test has its own @Rule Timeout.
if (runner instanceof ParentRunner) {
return BuckBlockJUnit4ClassRunner.hasTimeoutRule(((ParentRunner) runner).getTestClass());
}
Class<?> clazz = description.getTestClass();
while (clazz != null) {
for (Field field : clazz.getFields()) {
if (field.getAnnotationsByType(Rule.class).length > 0
&& field.getType().equals(Timeout.class)) {
return true;
}
}
clazz = clazz.getSuperclass();
}
return false;
}
private Primary getPartitionKey(Entry entry) {
Field[] fields = entry.getClass().getDeclaredFields();
for (Field field : fields) {
try {
PartitionKey[] partitionKey = field.getAnnotationsByType(PartitionKey.class);
if (partitionKey.length > 0) {
return (Primary) field.get(entry);
}
} catch (IllegalAccessException e) {
throw new FieldAccessException(field.getName(), entry.getClass().getName(), e);
}
}
throw new NoFieldMatchingAnnotationException(PartitionKey.class.getName(), entry.getClass().getName());
}
private Secondary getSortKey(Entry entry) {
Field[] fields = entry.getClass().getDeclaredFields();
for (Field field : fields) {
try {
SortKey[] sortKey = field.getAnnotationsByType(SortKey.class);
if (sortKey.length > 0) {
return (Secondary) field.get(entry);
}
} catch (IllegalAccessException e) {
throw new FieldAccessException(field.getName(), entry.getClass().getName(), e);
}
}
throw new NoFieldMatchingAnnotationException(SortKey.class.getName(), entry.getClass().getName());
}
public static <T> List<T> getPublicStaticFields(Class<?> fromClass, Class<T> ofType) throws IllegalAccessException {
List<T> list = new ArrayList<>();
for (Field field : fromClass.getDeclaredFields()) {
if (!Modifier.isPublic(field.getModifiers())) {
continue;
}
if (field.getAnnotationsByType(Deprecated.class).length > 0) {
continue;
}
T key = ofType.cast(field.get(null));
list.add(key);
}
return list;
}
private void handleFieldCollectionView(Class<?> entityClass, Map<String, Meta> result, String[] groups, Field field) {
final CollectionView[] views = field.getAnnotationsByType(CollectionView.class);
if (views.length > 0) {
for (CollectionView view : views) {
String[] viewGroups = view.groups();
if (viewGroups.length == 0) {
viewGroups = groups.clone();
}
for (String group : viewGroups) {
if (predicate.test(group)) {
final String entityClassName = entityClass.getName();
final Meta meta = metaCheck(entityClass, result, group);
final String name = view.name();
final Class<?> type = view.type();
if (isBlank(name)) {
throw new NullPointerException(format("%s 类的属性 %s 上使用注解@CollectionView时,注解的name属性不能为空", entityClassName, field.getName()));
}
if (!Collection.class.isAssignableFrom(type)) {
throw new IllegalArgumentException(format("%s 类上的属性 %s 上使用@CollectionView中注解时,注解type属性必须为Collection的实现类", entityClassName, field.getName()));
}
final Meta.CollectionField collectionField = new Meta.CollectionField();
collectionField.name = name;
collectionField.order = view.field().order();
collectionField.label = handleFieldLabel(field, view.field().label(), format("%s 类中的字段 %s 上使用@AssociationView时,label属性为空,并且没有加@Field注解", entityClass.getName(), field.getName()));
handleCollectionView(view, meta, type, collectionField, field.getType());
}
}
}
}
}
private void handleAssociationView(Class<?> entityClass, Map<String, Meta> result, String[] groups, Field field) {
final AssociationView[] associationViews = field.getAnnotationsByType(AssociationView.class);
if (associationViews.length > 0) {
for (AssociationView view : associationViews) {
String[] viewGroups = view.groups();
if (viewGroups.length == 0) {
viewGroups = groups.clone();
}
for (String group : viewGroups) {
if (predicate.test(group)) {
final Meta meta = metaCheck(entityClass, result, group);
final String name = getName(field, view.name());
final Meta.Field newField = new Meta.Field();
if (isBlank(view.associationGroup())) {
final Class<?> type = getType(field, view.type());
newField.type = type.getSimpleName();
addImport(meta, type);
} else {
newField.type = view.associationGroup();
}
newField.name = name;
final String label = view.field().label();
newField.order = view.field().order();
newField.label = handleFieldLabel(field, label, format("%s 类中的字段 %s 上使用@AssociationView时,label属性为空,并且没有加@Field注解", entityClass.getName(), field.getName()));
meta.getAssociationFields().add(newField);
}
}
}
}
}
private void handleFieldView(Class<?> entityClass, Map<String, Meta> result, String[] groups, Field field) {
final View[] views = field.getAnnotationsByType(View.class);
if (views.length > 0) {
for (View view : views) {
String[] viewGroups = view.groups();
if (viewGroups.length == 0) {
viewGroups = groups.clone();
}
for (String group : viewGroups) {
if (predicate.test(group)) {
final Meta meta = metaCheck(entityClass, result, group);
final String name = getName(field, view.name());
final Class<?> type = getType(field, view.type());
final Meta.Field newField = new Meta.Field();
newField.name = name;
newField.type = type.getSimpleName();
addImport(meta, type);
final String label = view.field().label();
newField.order = view.field().order();
newField.label = handleFieldLabel(field, label, format("%s 类中的字段 %s 上使用@View时,@Field注解label属性为空,并且没有加@Field注解", entityClass.getName(), field.getName()));
if (newField.name.equals(field.getName()) && newField.type.equals(field.getType().getSimpleName())) {
meta.getFields().add(newField);
} else {
meta.getAssociationFields().add(newField);
}
}
}
}
}
}
@Nullable
FlagProperty fieldPropertyAnnotation(Field javaField) {
FlagProperty property = null;
FlagProperty[] properties = javaField.getAnnotationsByType(FlagProperty.class);
if (properties.length > 0) {
property = properties[0];
Preconditions.checkNotNull(
Strings.emptyToNull(property.value()),
"FlagProperty can't be empty or null.");
}
return property;
}
private FlagData createFlagData(Class<?> declaringClass, Field field, Flag<?> flag) {
FlagDesc[] flagDescs = field.getAnnotationsByType(FlagDesc.class);
// TODO: Get nicer string for field
if (flagDescs.length == 0) {
throw new IllegalArgumentException("Flag '" + field + "' should be annotated with @FlagDesc");
}
if (flagDescs.length > 1) {
throw new IllegalArgumentException(
String.format(
"Flag '%s' has %d @FlagDesc annotations instead of 1.", field, flagDescs.length));
}
FlagDesc desc = flagDescs[0];
if (desc.name().isEmpty()) {
throw new IllegalArgumentException("Flag '" + field + "' name should be specified.");
}
if (!isLowerCamel(field.getName())) {
throw new IllegalArgumentException(
String.format(
"Flag '%s' variable name '%s' should be lowerCamelCase.", field, field.getName()));
}
String expectedUnderscoreName =
CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, field.getName());
if (!desc.name().equals(expectedUnderscoreName)) {
throw new IllegalArgumentException(
String.format(
"Flag '%s' name '%s' should be %s.", field, desc.name(), expectedUnderscoreName));
}
FlagData.Builder result =
FlagData.newBuilder()
.setName(desc.name())
.setClassName(declaringClass.getCanonicalName())
.setIsBooleanFlag(isBooleanFlag(field))
.setIsListFlag(isListFlag(field))
.setDescription(desc.description())
.setRequired(desc.required());
if (flag.getDefault() != null) {
if (result.getIsListFlag()) {
result.setDefault(
flag.getDefault().toString().replace("[", "").replace("]", "").replaceAll(", ", ","));
} else {
result.setDefault(flag.getDefault().toString());
}
}
return result.build();
}
private static boolean isOptionalProperty(Class beanClass, PropertyDescriptor beanProp) {
Field field = getField(beanClass, beanProp.getName());
return field != null && (field.getAnnotationsByType(Optional.class).length > 0);
}
@VisibleForTesting
// recursive (but doesn't search through nested objects, only nested extensions)
static String getExtensionData(String extensionName, Object extensionInstance, int depth)
throws IllegalAccessException {
StringBuilder result = new StringBuilder("");
// extension start block
result.append(spaces(depth)).append(extensionName).append(" {\n");
// all non-extension fields
for (Field field : extensionInstance.getClass().getSuperclass().getDeclaredFields()) {
// ignore synthetic fields (stuff added by compiler or instrumenter)
if (field.isSynthetic()) {
continue;
}
// This is just a helper for the extensions, don't show it
if (field.getType().equals(org.gradle.api.Project.class)) {
continue;
}
// ignore fields marked with InternalProperty
if (field.getAnnotationsByType(InternalProperty.class).length > 0) {
continue;
}
result.append(getFieldData(field, extensionInstance, depth + 1));
}
// all extension fields
Map<String, Object> map =
((ExtensionContainerInternal) ((ExtensionAware) extensionInstance).getExtensions())
.getAsMap();
for (String childExtensionName : map.keySet()) {
Object childExtensionInstance = map.get(childExtensionName);
// only expand out extensions we understand (we're ignoring the default ext group here, which
// is not ExtensionAware)
if (childExtensionInstance instanceof ExtensionAware) {
result.append(getExtensionData(childExtensionName, map.get(childExtensionName), depth + 1));
}
}
// extension end block
result.append(spaces(depth)).append("}\n");
return result.toString();
}
private static boolean isOptionalProperty(Class beanClass, PropertyDescriptor beanProp) {
Field field = getField(beanClass, beanProp.getName());
return field != null && (field.getAnnotationsByType(Optional.class).length > 0);
}