Java Code Examples for java.lang.reflect.Field#getModifiers()

The following examples show how to use java.lang.reflect.Field#getModifiers() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: LitePal   File: LitePalBase.java    License: Apache License 2.0 6 votes vote down vote up
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);
}
 
Example 2
Source Project: saros   File: MessageUtils.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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);
  }
}
 
Example 3
Source Project: hottub   File: Arguments.java    License: GNU General Public License v2.0 6 votes vote down vote up
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
        }
    }
}
 
Example 4
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;
        }
    }
}
 
Example 5
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));
}
 
Example 6
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;
        }
    }
}
 
Example 7
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
        }
    }
}
 
Example 8
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);
}
 
Example 9
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() );
  }
}
 
Example 10
Source Project: ACDD   File: Hack.java    License: MIT License 6 votes vote down vote up
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;
    }
}
 
Example 11
Source Project: MCPELauncher   File: ScriptManager.java    License: Apache License 2.0 5 votes vote down vote up
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");
}
 
Example 12
Source Project: Aria   File: SqlUtil.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 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);
}
 
Example 13
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();
		}
	}
}
 
Example 14
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;
}
 
Example 15
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);
}
 
Example 16
/**
 * 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);
}
 
Example 17
Source Project: stetho   File: ViewDescriptor.java    License: MIT License 4 votes vote down vote up
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);
  }
}
 
Example 18
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);
}
 
Example 19
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);
}
 
Example 20
Source Project: RapidORM   File: ReflectionUtils.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * ************************************** modifier ****************************************
 */
public static boolean isModifier(Field field, int modifier) {
    return (field.getModifiers() & modifier) == modifier;
}