下面列出了java.lang.reflect.Field#isSynthetic ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* inner recursively dispatch field with reflect access
*
* @param clazz class of two instance
* @param left the left object to handle
* @param right the right object to handle
* @param paths current node paths
* @param comparator integrated comparator
*/
private void innerCompare(Class<?> clazz, Object left, Object right, List<Path> paths, IntegratedComparator comparator) {
Field[] fields = clazz.getDeclaredFields();
for (Field field : fields) {
if (field.isSynthetic() || isTransient(field.getModifiers()) || isStatic(field.getModifiers())) {
continue;
}
boolean accessible = field.isAccessible();
// recursively dispatch with integrated comparator
try {
field.setAccessible(true);
comparator.dispatch(field.get(left), field.get(right), comparator.declarePath(paths, field.getName()));
} catch (Exception e) {
// this may not happen
throw new RuntimeException("illegal access with filed", e);
} finally {
field.setAccessible(accessible);
}
}
Class<?> superClazz = clazz.getSuperclass();
while (superClazz != null && superClazz != Object.class) {
innerCompare(superClazz, left, right, paths, comparator);
superClazz = superClazz.getSuperclass();
}
}
/**
* Get declared fields in the whole class hierarchy.
* If there are fields with the same name in super-class and sub-class,
* fields in the sub-class with be returned only.
*/
public static List<Field> findFields(Class<?> clazz) {
Map<String, Field> fields = new LinkedHashMap<>();
Class<?> current = clazz;
while (current != null) {
for (Field field: current.getDeclaredFields()) {
if (!field.isSynthetic()
&& !Modifier.isStatic(field.getModifiers())
&& !fields.containsKey(field.getName())) {
fields.put(field.getName(), field);
}
}
current = current.getSuperclass();
}
return new ArrayList<Field>(fields.values());
}
private static void createTerrainMapping() {
if(terrainMapping.isEmpty()) {
for (Field f : Terrain.class.getDeclaredFields()) {
if (f.isSynthetic()) {
continue;
}
int value;
try {
value = f.getInt(null);
} catch (IllegalAccessException | IllegalArgumentException ignored) {
continue;
}
String name = f.getName();
terrainMapping.put(name, value);
}
}
}
@Override
protected void discover() {
for (final Field field : ReflectionUtils.getDeclaredAndInheritedFields(getClazz(), true)) {
field.setAccessible(true);
final int fieldMods = field.getModifiers();
if (field.isAnnotationPresent(Transient.class)
|| field.isSynthetic() && (fieldMods & Modifier.TRANSIENT) == Modifier.TRANSIENT
|| getMapper().getOptions().isActLikeSerializer() && ((fieldMods & Modifier.TRANSIENT) == Modifier.TRANSIENT)
|| getMapper().getOptions().isIgnoreFinals() && ((fieldMods & Modifier.FINAL) == Modifier.FINAL)) {
// ignore these
} else {
getPersistenceFields().add(mapField(field));
}
}
}
/**
* Tries to find a class fields. Supports inheritance and doesn't return synthetic fields.
*
* @param beanClass class to be searched for
* @param fieldName field name
* @return a list of found fields
*/
public static Field findClassField(Class<?> beanClass, String fieldName) {
Class<?> currentClass = beanClass;
while (currentClass != null && currentClass != Object.class) {
for (Field field : currentClass.getDeclaredFields()) {
if (field.isSynthetic()) {
continue;
}
if (field.getName().equals(fieldName)) {
return field;
}
}
currentClass = currentClass.getSuperclass();
}
return null;
}
private List<Field> filterSyntheticFields(List<Field> tmpFields) {
// 过滤 synthetic 属性
List<Field> fieldsList = new ArrayList<Field>();
for (Field field : tmpFields) {
if (!field.isSynthetic()) {
fieldsList.add(field);
}
}
return fieldsList;
}
private void addOuterClassFields(Class<?> type, Collection<String> fields) {
for (Field field : type.getDeclaredFields()) {
if (field.isSynthetic()) {
fields.add(field.getName());
}
}
if (type.getSuperclass() != null) {
addOuterClassFields(type.getSuperclass(), fields);
}
}
@SneakyThrows
private static void addMappingForClass(Class<?> clazz) {
for (Field f : clazz.getDeclaredFields()) {
if (f.isSynthetic()) {
continue;
}
int key = f.getInt(null);
String name = f.getName();
keyToInt.put(name, key);
}
}
private void visitObject(Class<?> objectClass, Field owner, String path) {
if (visitedClasses.contains(objectClass))
throw new Error("class must not have circular reference, field=" + Fields.path(owner));
visitedClasses.add(objectClass);
validateClass(objectClass);
if (visitor != null) visitor.visitClass(objectClass, path);
Field[] fields = objectClass.getDeclaredFields();
for (Field field : fields) {
if (field.isSynthetic()) continue; // ignore dynamic/generated field, e.g. jacoco
if (Modifier.isStatic(field.getModifiers()) && Modifier.isFinal(field.getModifiers())) continue; // ignore all static final field
validateField(field);
if (visitor != null) visitor.visitField(field, path);
String fieldPath = path(path, field.getName());
Type fieldType = field.getGenericType();
if (GenericTypes.isList(fieldType)) {
if (!allowChild) throw new Error("list field is not allowed, field=" + Fields.path(field));
visitList(fieldType, field, fieldPath);
} else if (GenericTypes.isMap(fieldType)) {
if (!allowChild) throw new Error("map field is not allowed, field=" + Fields.path(field));
visitMap(fieldType, field, fieldPath);
} else {
visitValue(GenericTypes.rawClass(fieldType), field, fieldPath);
}
}
visitedClasses.remove(objectClass);
}
public static void resetCounters() throws Exception {
Class<?> cl = SplitLogCounters.class;
for (Field fld : cl.getDeclaredFields()) {
/* Guard against source instrumentation. */
if ((!fld.isSynthetic()) && (LongAdder.class.isAssignableFrom(fld.getType()))) {
((LongAdder)fld.get(null)).reset();
}
}
}
@SuppressWarnings("unchecked")
public static <T extends Enum<?>> T addEnum(Class<T> enumType, String enumName, Class<?>[] paramTypes, Object[] paramValues) {
if (!Enum.class.isAssignableFrom(enumType)) {
throw new RuntimeException("class " + enumType + " is not an instance of Enum");
}
try {
Field valuesField = null;
for (Field field : enumType.getDeclaredFields()) {
if (field.isSynthetic() && field.getType().isArray() && field.getType().getComponentType().equals(enumType)) {
valuesField = field;
break;
}
}
valuesField.setAccessible(true);
T[] previousValues = (T[]) valuesField.get(enumType);
List<T> values = new ArrayList<T>(Arrays.asList(previousValues));
T newValue = (T) makeEnum(enumType, enumName, values.size(), paramTypes, paramValues);
values.add(newValue);
setField(valuesField, null, values.toArray((Enum[]) Array.newInstance(enumType, 0)));
cleanEnumCache(enumType);
return newValue;
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e.getMessage(), e);
}
}
public boolean isApplicable(Field field, SchemaPropertyContext context) {
return !Modifier.isStatic(field.getModifiers()) && //
!field.isSynthetic() && //
!IGNORE_ANNOTATIONS.stream().anyMatch(a -> field.getAnnotation(a) != null) && //
isApplicableFor(field, context) && //
isApplicableForPathParam(field);
}
private static List<String> determineExtensionProps() {
final List<String> props = new ArrayList<>();
for (final Field f : CheckForbiddenApisExtension.class.getDeclaredFields()) {
final int mods = f.getModifiers();
if (Modifier.isPublic(mods) && !f.isSynthetic() && !Modifier.isStatic(mods)) {
props.add(f.getName());
}
}
return Collections.unmodifiableList(props);
}
@SuppressWarnings("unchecked")
public static <T extends Enum<?>> T addEnum(Class<T> enumType, String enumName, Class<?>[] paramTypes, Object[] paramValues) {
if (!Enum.class.isAssignableFrom(enumType)) {
throw new RuntimeException("class " + enumType + " is not an instance of Enum");
}
try {
Field valuesField = null;
for (Field field : enumType.getDeclaredFields()) {
if (field.isSynthetic() && field.getType().isArray() && field.getType().getComponentType().equals(enumType)) {
valuesField = field;
break;
}
}
valuesField.setAccessible(true);
T[] previousValues = (T[]) valuesField.get(enumType);
List<T> values = new ArrayList<T>(Arrays.asList(previousValues));
T newValue = (T) makeEnum(enumType, enumName, values.size(), paramTypes, paramValues);
values.add(newValue);
setField(valuesField, null, values.toArray((Enum[]) Array.newInstance(enumType, 0)));
cleanEnumCache(enumType);
return newValue;
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e.getMessage(), e);
}
}
private void findAnnotation(
final Collection<Type> values,
final Map<DocumentField.Type, Field> fields,
final Field field) {
final DocumentField annotation = field.getAnnotation(DocumentField.class);
if (annotation != null && !field.isSynthetic() && !Modifier.isStatic(field.getModifiers())
&& String.class.isAssignableFrom(field.getType())) {
final Type value = annotation.value();
if (values.contains(value)) {
field.setAccessible(true);
fields.put(value, field);
values.remove(value);
}
}
}
public static boolean isPublicInstanceField(Field field) {
return Modifier.isPublic(field.getModifiers())
&& !Modifier.isStatic(field.getModifiers())
&& !Modifier.isFinal(field.getModifiers())
&& !field.isSynthetic();
}
/**
* Validates that the given class is effectively static and has no instance state.
*
* @param source the class the validate
*/
public void validate(Class<?> source) throws InvalidModelRuleDeclarationException {
// TODO - exceptions thrown here should point to some extensive documentation on the concept of class rule sources
int modifiers = source.getModifiers();
if (Modifier.isInterface(modifiers)) {
throw invalid(source, "must be a class, not an interface");
}
if (Modifier.isAbstract(modifiers)) {
throw invalid(source, "class cannot be abstract");
}
if (source.getEnclosingClass() != null) {
if (Modifier.isStatic(modifiers)) {
if (Modifier.isPrivate(modifiers)) {
throw invalid(source, "class cannot be private");
}
} else {
throw invalid(source, "enclosed classes must be static and non private");
}
}
Class<?> superclass = source.getSuperclass();
if (!superclass.equals(Object.class)) {
throw invalid(source, "cannot have superclass");
}
Constructor<?>[] constructors = source.getDeclaredConstructors();
if (constructors.length > 1) {
throw invalid(source, "cannot have more than one constructor");
}
Constructor<?> constructor = constructors[0];
if (constructor.getParameterTypes().length > 0) {
throw invalid(source, "constructor cannot take any arguments");
}
Field[] fields = source.getDeclaredFields();
for (Field field : fields) {
int fieldModifiers = field.getModifiers();
if (!field.isSynthetic() && !(Modifier.isStatic(fieldModifiers) && Modifier.isFinal(fieldModifiers))) {
throw invalid(source, "field " + field.getName() + " is not static final");
}
}
}
private static boolean matches(Class<?> type, Object left, Object right, Set<Pair> visited) throws Exception {
if (!visited.add(new Pair(left, right))) {
return true;
} else if (mockingDetails(left).isMock() || mockingDetails(left).isSpy() || mockingDetails(right).isMock() || mockingDetails(right).isSpy()) {
return left == right;
}
while (type.getName().startsWith("net.bytebuddy.")) {
for (Field field : type.getDeclaredFields()) {
if (Modifier.isStatic(field.getModifiers()) || field.isSynthetic() && !field.getName().equals("this$0")) {
continue;
}
HashCodeAndEqualsPlugin.ValueHandling valueHandling = field.getAnnotation(HashCodeAndEqualsPlugin.ValueHandling.class);
if (valueHandling != null && valueHandling.value() == HashCodeAndEqualsPlugin.ValueHandling.Sort.IGNORE) {
continue;
}
field.setAccessible(true);
if (field.getType() == boolean.class) {
if (field.getBoolean(left) != field.getBoolean(right)) {
return false;
}
} else if (field.getType() == byte.class) {
if (field.getBoolean(left) != field.getBoolean(right)) {
return false;
}
} else if (field.getType() == short.class) {
if (field.getShort(left) != field.getShort(right)) {
return false;
}
} else if (field.getType() == char.class) {
if (field.getChar(left) != field.getChar(right)) {
return false;
}
} else if (field.getType() == int.class) {
if (field.getInt(left) != field.getInt(right)) {
return false;
}
} else if (field.getType() == long.class) {
if (field.getLong(left) != field.getLong(right)) {
return false;
}
} else if (field.getType() == float.class) {
if (field.getFloat(left) != field.getFloat(right)) {
return false;
}
} else if (field.getType() == double.class) {
if (field.getDouble(left) != field.getDouble(right)) {
return false;
}
} else if (field.getType().isEnum()) {
if (field.get(left) != field.get(right)) {
return false;
}
} else {
Object leftObject = field.get(left), rightObject = field.get(right);
if (mockingDetails(leftObject).isMock() || mockingDetails(rightObject).isSpy() || mockingDetails(rightObject).isMock() || mockingDetails(rightObject).isSpy()) {
if (leftObject != rightObject) {
return false;
}
} else if (Iterable.class.isAssignableFrom(field.getType())) {
if (rightObject == null) {
return false;
}
Iterator<?> rightIterable = ((Iterable<?>) rightObject).iterator();
for (Object instance : (Iterable<?>) leftObject) {
if (!rightIterable.hasNext() || !matches(instance.getClass(), instance, rightIterable.next(), visited)) {
return false;
}
}
} else if (field.getType().getName().startsWith("net.bytebuddy.")) {
if (leftObject == null ? rightObject != null : !matches(leftObject.getClass(), leftObject, rightObject, visited)) {
return false;
}
} else {
if (leftObject == null ? rightObject != null : !leftObject.equals(rightObject)) {
return false;
}
}
}
}
type = type.getSuperclass();
}
return true;
}
private void processTypes(final Set<Class<?>> types) {
while (!types.isEmpty()) {
final Iterator<Class<?>> iter = types.iterator();
final Class<?> type = iter.next();
iter.remove();
synchronized(type) {
if (annotatedTypes.contains(type)) {
continue;
}
try {
if (type.isPrimitive()) {
continue;
}
addParametrizedTypes(type, types);
processConverterAnnotations(type);
processAliasAnnotation(type, types);
processAliasTypeAnnotation(type);
if (type.isInterface()) {
continue;
}
processImplicitCollectionAnnotation(type);
final Field[] fields = type.getDeclaredFields();
for (int i = 0; i < fields.length; i++ ) {
final Field field = fields[i];
if (field.isEnumConstant()
|| (field.getModifiers() & (Modifier.STATIC | Modifier.TRANSIENT)) > 0) {
continue;
}
addParametrizedTypes(field.getGenericType(), types);
if (field.isSynthetic()) {
continue;
}
processFieldAliasAnnotation(field);
processAsAttributeAnnotation(field);
processImplicitAnnotation(field);
processOmitFieldAnnotation(field);
processLocalConverterAnnotation(field);
}
} finally {
annotatedTypes.add(type);
}
}
}
}
public static boolean isPublicInstanceField(Field field) {
return Modifier.isPublic(field.getModifiers())
&& !Modifier.isStatic(field.getModifiers())
&& !Modifier.isFinal(field.getModifiers())
&& !field.isSynthetic();
}