下面列出了java.lang.reflect.Field#getModifiers ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private void recursiveSupportedGenericFields(Class<?> clazz, List<Field> supportedGenericFields) {
if (clazz == LitePalSupport.class || clazz == Object.class) {
return;
}
Field[] fields = clazz.getDeclaredFields();
if (fields != null && fields.length > 0) {
for (Field field : fields) {
Column annotation = field.getAnnotation(Column.class);
if (annotation != null && annotation.ignore()) {
continue;
}
int modifiers = field.getModifiers();
if (!Modifier.isStatic(modifiers) && isCollection(field.getType())) {
String genericTypeName = getGenericTypeName(field);
if (BaseUtility.isGenericTypeSupported(genericTypeName) || clazz.getName().equalsIgnoreCase(genericTypeName)) {
supportedGenericFields.add(field);
}
}
}
}
recursiveSupportedGenericFields(clazz.getSuperclass(), supportedGenericFields);
}
/**
* Loads strings in to static variables from property file.
*
* @param propertyFile
* @param clazz
*/
public static void initializeMessages(String propertyFile, Class<?> clazz) {
try {
log.info("Loading bundle [" + propertyFile + "]");
ResourceBundle resourceBundle = ResourceBundle.getBundle(propertyFile, Locale.getDefault());
for (Field f : clazz.getFields()) {
String fieldName = f.getName();
String fieldValue = resourceBundle.getString(fieldName);
int modifier = f.getModifiers();
if (Modifier.isPublic(modifier)
&& !Modifier.isFinal(modifier)
&& f.getType().equals(String.class)) {
f.set(clazz, fieldValue);
}
}
} catch (Exception e) {
log.error("Failed to initialize messages", e);
}
}
protected void setDebugFlags( String args )
{
StringTokenizer st = new StringTokenizer( args, "," ) ;
while (st.hasMoreTokens()) {
String token = st.nextToken() ;
// If there is a public boolean data member in this class
// named token + "DebugFlag", set it to true.
try {
Field fld = this.getClass().getField( token + "DebugFlag" ) ;
int mod = fld.getModifiers() ;
if (Modifier.isPublic( mod ) && !Modifier.isStatic( mod ))
if (fld.getType() == boolean.class)
fld.setBoolean( this, true ) ;
} catch (Exception exc) {
// ignore it
}
}
}
public FieldReflection(Field f, boolean supressAccessorWarnings) {
super((Class<ValueT>) f.getType());
this.f = f;
int mod = f.getModifiers();
if (!Modifier.isPublic(mod) || Modifier.isFinal(mod) || !Modifier.isPublic(f.getDeclaringClass().getModifiers())) {
try {
// attempt to make it accessible, but do so in the security context of the calling application.
// don't do this in the doPrivilege block, as that would create a security hole for anyone
// to make any field accessible.
f.setAccessible(true);
} catch (SecurityException e) {
if ((!accessWarned) && (!supressAccessorWarnings)) {
// this happens when we don't have enough permission.
logger.log(Level.WARNING, Messages.UNABLE_TO_ACCESS_NON_PUBLIC_FIELD.format(
f.getDeclaringClass().getName(),
f.getName()),
e);
}
accessWarned = true;
}
}
}
private static boolean hasIllegalFieldVisibility(Field field) {
final int modifiers = field.getModifiers();
if (Modifier.isPrivate(modifiers)) {
return false;
} else if (!Modifier.isStatic(modifiers) || !Modifier.isFinal(modifiers)) {
return true;
}
// Field is non-private, static and final
Class<?> valueType;
if (Collection.class.isAssignableFrom(field.getType()) || Map.class.isAssignableFrom(field.getType())) {
// For collections/maps, need to check the actual type to ensure it's an unmodifiable implementation
Object value = ReflectionTestUtils.getFieldValue(field, null);
valueType = value.getClass();
} else {
valueType = field.getType();
}
// Field is static, final, and not private -> check that it is immutable type
return IMMUTABLE_TYPES.stream()
.noneMatch(immutableType -> immutableType.isAssignableFrom(valueType));
}
public FieldReflection(Field f, boolean supressAccessorWarnings) {
super((Class<ValueT>) f.getType());
this.f = f;
int mod = f.getModifiers();
if (!Modifier.isPublic(mod) || Modifier.isFinal(mod) || !Modifier.isPublic(f.getDeclaringClass().getModifiers())) {
try {
// attempt to make it accessible, but do so in the security context of the calling application.
// don't do this in the doPrivilege block, as that would create a security hole for anyone
// to make any field accessible.
f.setAccessible(true);
} catch (SecurityException e) {
if ((!accessWarned) && (!supressAccessorWarnings)) {
// this happens when we don't have enough permission.
logger.log(Level.WARNING, Messages.UNABLE_TO_ACCESS_NON_PUBLIC_FIELD.format(
f.getDeclaringClass().getName(),
f.getName()),
e);
}
accessWarned = true;
}
}
}
protected void setDebugFlags( String args )
{
StringTokenizer st = new StringTokenizer( args, "," ) ;
while (st.hasMoreTokens()) {
String token = st.nextToken() ;
// If there is a public boolean data member in this class
// named token + "DebugFlag", set it to true.
try {
Field fld = this.getClass().getField( token + "DebugFlag" ) ;
int mod = fld.getModifiers() ;
if (Modifier.isPublic( mod ) && !Modifier.isStatic( mod ))
if (fld.getType() == boolean.class)
fld.setBoolean( this, true ) ;
} catch (Exception exc) {
// ignore it
}
}
}
public static <T, V> long getFieldOffet(Class<T> tclass,
Class<V> expectedFieldClass, String fieldName) {
Field field = null;
Class<?> fieldClass = null;
int modifiers = 0;
try {
field = tclass.getDeclaredField(fieldName);
modifiers = field.getModifiers();
fieldClass = field.getType();
} catch (Exception ex) {
throw new RuntimeException(ex);
}
if (expectedFieldClass != fieldClass) {
throw new ClassCastException("expectedFieldClass=" + expectedFieldClass
+ ", actual fieldClass=" + fieldClass);
}
if (!Modifier.isVolatile(modifiers)) {
throw new IllegalArgumentException("Field '" + fieldName + "' in '"
+ tclass.getName() + "' must be volatile");
}
return unsafe.objectFieldOffset(field);
}
public static synchronized void registerClass( final Class c ) {
// Log.debug ("Registering stylekeys from " + c);
try {
final Field[] fields = c.getFields();
for ( int i = 0; i < fields.length; i++ ) {
final Field field = fields[i];
final int modifiers = field.getModifiers();
if ( Modifier.isPublic( modifiers ) && Modifier.isStatic( modifiers ) ) {
if ( Modifier.isFinal( modifiers ) == false ) {
logger.warn( "Invalid implementation: StyleKeys should be 'public static final': " + c );
}
if ( field.getType().isAssignableFrom( StyleKey.class ) ) {
// noinspection UnusedDeclaration
final StyleKey value = (StyleKey) field.get( null );
// ignore the returned value, all we want is to trigger the key
// creation
// Log.debug ("Loaded key " + value);
}
}
}
} catch ( IllegalAccessException e ) {
// wont happen, we've checked it..
logger.warn( "Unable to register keys from " + c.getName() );
}
}
HackedField(Class<C> cls, String name, int modifier) throws HackAssertionException {
Field field = null;
if (cls == null) {
this.mField = null;
return;
}
try {
field = cls.getDeclaredField(name);
if (modifier > 0 && (field.getModifiers() & modifier) != modifier) {
Hack.fail(new HackAssertionException(field
+ " does not match modifiers: " + modifier));
}
field.setAccessible(true);
} catch (Exception e) {
HackAssertionException hackAssertionException = new HackAssertionException(e);
hackAssertionException.setHackedClass(cls);
hackAssertionException.setHackedFieldName(name);
Hack.fail(hackAssertionException);
} finally {
this.mField = field;
}
}
private static void appendApiClassConstants(StringBuilder builder, Class<?> clazz) {
String className = clazz.getSimpleName();
for (Field field : clazz.getFields()) {
int fieldModifiers = field.getModifiers();
if (!Modifier.isStatic(fieldModifiers) || !Modifier.isPublic(fieldModifiers))
continue;
builder.append(className).append(".").append(field.getName()).append(";\n");
}
builder.append("\n");
}
/**
* shadow$_klass_、shadow$_monitor_、{@link Ignore}、rowID、{@link Field#isSynthetic()}、{@link
* Modifier#isFinal(int)}、{@link Modifier#isStatic(int)}将被忽略
*
* @return true 忽略该字段
*/
static boolean isIgnore(Field field) {
// field.isSynthetic(), 使用as热启动App时,AS会自动给你的class添加change字段
Ignore ignore = field.getAnnotation(Ignore.class);
int modifiers = field.getModifiers();
String fieldName = field.getName();
return (ignore != null && ignore.value()) || fieldName.equals("rowID") || fieldName.equals(
AriaConfig.IGNORE_CLASS_KLASS) || fieldName.equals(AriaConfig.IGNORE_CLASS_MONITOR)
|| field.isSynthetic() || Modifier
.isStatic(modifiers) || Modifier.isFinal(modifiers);
}
private void stopAllExecutors() throws IllegalArgumentException, IllegalAccessException {
Class<?> clazz = utilClass.getClazz();
for (Field field: clazz.getDeclaredFields()) {
if ((field.getModifiers() & Modifier.STATIC) > 0 && field.getType().equals(ExecutorService.class)) {
field.setAccessible(true);
ExecutorService exec = (ExecutorService) field.get(null);
exec.shutdownNow();
}
}
}
public List<FeatureKey<?>> getRequiredFeatures() throws IllegalAccessException {
List<FeatureKey<?>> features = new ArrayList<>();
for (Field field: FeatureKey.class.getDeclaredFields()) {
int modifiers = field.getModifiers();
if (Modifier.isStatic(modifiers) && Modifier.isPublic(modifiers)) {
if (field.getType().isAssignableFrom(FeatureKey.class)) {
features.add((FeatureKey<?>) field.get(null));
}
}
}
return features;
}
AtomicReferenceFieldUpdaterImpl(final Class<T> tclass,
final Class<V> vclass,
final String fieldName,
final Class<?> caller) {
final Field field;
final Class<?> fieldClass;
final int modifiers;
try {
field = AccessController.doPrivileged(
new PrivilegedExceptionAction<Field>() {
public Field run() throws NoSuchFieldException {
return tclass.getDeclaredField(fieldName);
}
});
modifiers = field.getModifiers();
sun.reflect.misc.ReflectUtil.ensureMemberAccess(
caller, tclass, null, modifiers);
ClassLoader cl = tclass.getClassLoader();
ClassLoader ccl = caller.getClassLoader();
if ((ccl != null) && (ccl != cl) &&
((cl == null) || !isAncestor(cl, ccl))) {
sun.reflect.misc.ReflectUtil.checkPackageAccess(tclass);
}
fieldClass = field.getType();
} catch (PrivilegedActionException pae) {
throw new RuntimeException(pae.getException());
} catch (Exception ex) {
throw new RuntimeException(ex);
}
if (vclass != fieldClass)
throw new ClassCastException();
if (vclass.isPrimitive())
throw new IllegalArgumentException("Must be reference type");
if (!Modifier.isVolatile(modifiers))
throw new IllegalArgumentException("Must be volatile type");
// Access to protected field members is restricted to receivers only
// of the accessing class, or one of its subclasses, and the
// accessing class must in turn be a subclass (or package sibling)
// of the protected member's defining class.
// If the updater refers to a protected field of a declaring class
// outside the current package, the receiver argument will be
// narrowed to the type of the accessing class.
this.cclass = (Modifier.isProtected(modifiers) &&
tclass.isAssignableFrom(caller) &&
!isSamePackage(tclass, caller))
? caller : tclass;
this.tclass = tclass;
this.vclass = vclass;
this.offset = U.objectFieldOffset(field);
}
/**
* Reader and Writer will ignore static and final fields.
* @return true if the field has to be ignored by the writer.
*/
public static boolean ignoreField(final Field field)
{
final int modifiers = field.getModifiers();
return Modifier.isStatic(modifiers) || Modifier.isFinal(modifiers) == true || Modifier.isTransient(modifiers);
}
private void getStylesFromObject(
View view,
String name,
Object value,
@Nullable ViewDebug.ExportedProperty annotation,
StyleAccumulator styles) {
if (annotation == null || !annotation.deepExport() || value == null) {
return;
}
Field[] fields = value.getClass().getFields();
for (Field field : fields) {
int modifiers = field.getModifiers();
if (Modifier.isStatic(modifiers)) {
continue;
}
Object propertyValue;
try {
field.setAccessible(true);
propertyValue = field.get(value);
} catch (IllegalAccessException e) {
LogUtil.e(
e,
"failed to get property of name: \"" + name + "\" of object: " + String.valueOf(value));
return;
}
String propertyName = field.getName();
switch (propertyName) {
case "bottomMargin":
propertyName = "margin-bottom";
break;
case "topMargin":
propertyName = "margin-top";
break;
case "leftMargin":
propertyName = "margin-left";
break;
case "rightMargin":
propertyName = "margin-right";
break;
default:
String annotationPrefix = annotation.prefix();
propertyName = convertViewPropertyNameToCSSName(
(annotationPrefix == null) ? propertyName : (annotationPrefix + propertyName));
break;
}
ViewDebug.ExportedProperty subAnnotation =
field.getAnnotation(ViewDebug.ExportedProperty.class);
getStyleFromValue(
view,
propertyName,
propertyValue,
subAnnotation,
styles);
}
}
AtomicReferenceFieldUpdaterImpl(final Class<T> tclass,
final Class<V> vclass,
final String fieldName,
final Class<?> caller) {
final Field field;
final Class<?> fieldClass;
final int modifiers;
try {
field = AccessController.doPrivileged(
new PrivilegedExceptionAction<Field>() {
public Field run() throws NoSuchFieldException {
return tclass.getDeclaredField(fieldName);
}
});
modifiers = field.getModifiers();
sun.reflect.misc.ReflectUtil.ensureMemberAccess(
caller, tclass, null, modifiers);
ClassLoader cl = tclass.getClassLoader();
ClassLoader ccl = caller.getClassLoader();
if ((ccl != null) && (ccl != cl) &&
((cl == null) || !isAncestor(cl, ccl))) {
sun.reflect.misc.ReflectUtil.checkPackageAccess(tclass);
}
fieldClass = field.getType();
} catch (PrivilegedActionException pae) {
throw new RuntimeException(pae.getException());
} catch (Exception ex) {
throw new RuntimeException(ex);
}
if (vclass != fieldClass)
throw new ClassCastException();
if (vclass.isPrimitive())
throw new IllegalArgumentException("Must be reference type");
if (!Modifier.isVolatile(modifiers))
throw new IllegalArgumentException("Must be volatile type");
// Access to protected field members is restricted to receivers only
// of the accessing class, or one of its subclasses, and the
// accessing class must in turn be a subclass (or package sibling)
// of the protected member's defining class.
// If the updater refers to a protected field of a declaring class
// outside the current package, the receiver argument will be
// narrowed to the type of the accessing class.
this.cclass = (Modifier.isProtected(modifiers) &&
tclass.isAssignableFrom(caller) &&
!isSamePackage(tclass, caller))
? caller : tclass;
this.tclass = tclass;
this.vclass = vclass;
this.offset = U.objectFieldOffset(field);
}
LockedUpdater(final Class<T> tclass, final String fieldName,
final Class<?> caller) {
Field field = null;
int modifiers = 0;
try {
field = AccessController.doPrivileged(
new PrivilegedExceptionAction<Field>() {
public Field run() throws NoSuchFieldException {
return tclass.getDeclaredField(fieldName);
}
});
modifiers = field.getModifiers();
sun.reflect.misc.ReflectUtil.ensureMemberAccess(
caller, tclass, null, modifiers);
ClassLoader cl = tclass.getClassLoader();
ClassLoader ccl = caller.getClassLoader();
if ((ccl != null) && (ccl != cl) &&
((cl == null) || !isAncestor(cl, ccl))) {
sun.reflect.misc.ReflectUtil.checkPackageAccess(tclass);
}
} catch (PrivilegedActionException pae) {
throw new RuntimeException(pae.getException());
} catch (Exception ex) {
throw new RuntimeException(ex);
}
if (field.getType() != long.class)
throw new IllegalArgumentException("Must be long type");
if (!Modifier.isVolatile(modifiers))
throw new IllegalArgumentException("Must be volatile type");
// Access to protected field members is restricted to receivers only
// of the accessing class, or one of its subclasses, and the
// accessing class must in turn be a subclass (or package sibling)
// of the protected member's defining class.
// If the updater refers to a protected field of a declaring class
// outside the current package, the receiver argument will be
// narrowed to the type of the accessing class.
this.cclass = (Modifier.isProtected(modifiers) &&
tclass.isAssignableFrom(caller) &&
!isSamePackage(tclass, caller))
? caller : tclass;
this.tclass = tclass;
this.offset = U.objectFieldOffset(field);
}
/**
* ************************************** modifier ****************************************
*/
public static boolean isModifier(Field field, int modifier) {
return (field.getModifiers() & modifier) == modifier;
}