Java Code Examples for java.lang.reflect.Modifier#isFinal()

The following examples show how to use java.lang.reflect.Modifier#isFinal() . 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 File: CSVApisUtil.java    From sofa-acts with Apache License 2.0 6 votes vote down vote up
public static Map<String, Field> findTargetClsFields(Class<?> cls) {
    if (isWrapClass(cls)) {
        return null;
    }
    ReflectUtils refUtil = ReflectUtils.getInstance();
    ClassFields<?> clsFiled = refUtil.analyzeClass(cls);
    List<Field> getPro = clsFiled.getClassData().getFields();
    Map<String, Field> reClsProp = new HashMap<String, Field>();
    for (Field proValue : getPro) {
        if (Modifier.isFinal(proValue.getModifiers())
            || Modifier.isStatic(proValue.getModifiers())) {
            continue;
        }
        String propName = proValue.getName();
        reClsProp.put(propName, proValue);
    }

    return reClsProp;
}
 
Example 2
Source File: Accessor.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
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 3
Source File: DoFnSignatures.java    From beam with Apache License 2.0 6 votes vote down vote up
/**
 * Returns successfully if the field is valid, otherwise throws an exception via its {@link
 * ErrorReporter} parameter describing validation failures for the timer declaration.
 */
private static void validateTimerField(
    ErrorReporter errors, Map<String, TimerDeclaration> declarations, String id, Field field) {
  if (declarations.containsKey(id)) {
    errors.throwIllegalArgument(
        "Duplicate %s \"%s\", used on both of [%s] and [%s]",
        format(DoFn.TimerId.class),
        id,
        field.toString(),
        declarations.get(id).field().toString());
  }

  Class<?> timerSpecRawType = field.getType();
  if (!(timerSpecRawType.equals(TimerSpec.class))) {
    errors.throwIllegalArgument(
        "%s annotation on non-%s field [%s]",
        format(DoFn.TimerId.class), format(TimerSpec.class), field.toString());
  }

  if (!Modifier.isFinal(field.getModifiers())) {
    errors.throwIllegalArgument(
        "Non-final field %s annotated with %s. Timer declarations must be final.",
        field.toString(), format(DoFn.TimerId.class));
  }
}
 
Example 4
Source File: PojoTypeConverter.java    From marble with Apache License 2.0 5 votes vote down vote up
public static List<Field> getAllDeclaredFields(Class<?> clazz) {
  List<Field> result = new ArrayList<Field>();
  while (clazz != null && !clazz.equals(Object.class)) {
    Field[] fields = clazz.getDeclaredFields();
    for (Field field : fields) {
      if (Modifier.isTransient(field.getModifiers()) || Modifier.isStatic(
          field.getModifiers()) || Modifier.isFinal(field.getModifiers())) {
        continue;
      }
      result.add(field);
    }
    clazz = clazz.getSuperclass();
  }
  return result;
}
 
Example 5
Source File: DatabaseUtils.java    From Cangol-appcore with Apache License 2.0 5 votes vote down vote up
/**
 * 创建表索引
 *
 * @param db
 * @param clazz
 */
public static void createIndex(SQLiteDatabase db, Class<?> clazz, String indexName, String... fieldNames) {
    if (clazz.isAnnotationPresent(DatabaseTable.class)) {
        final DatabaseTable table = clazz.getAnnotation(DatabaseTable.class);
        final String tableName = "".equals(table.value()) ? clazz.getSimpleName() : table.value();
        final StringBuilder sql = new StringBuilder("CREATE INDEX ");
        sql.append(indexName).append(" on ").append(tableName).append('(');
        Field field = null;
        String columnName = null;
        for (int i = 0; i < fieldNames.length; i++) {
            try {
                field = clazz.getDeclaredField(fieldNames[i]);
                field.setAccessible(true);
                if (field.isEnumConstant() || Modifier.isFinal(field.getModifiers()) || Modifier.isTransient(field.getModifiers())) {
                    continue;
                } else if (field.isAnnotationPresent(DatabaseField.class)) {
                    final DatabaseField dbField = field.getAnnotation(DatabaseField.class);
                    columnName = "".equals(dbField.value()) ? field.getName() : dbField.value();
                    sql.append(columnName);
                    if (i < fieldNames.length - 1)
                        sql.append(',');
                }
            } catch (NoSuchFieldException e) {
                Log.e(e.getMessage());
            }
        }
        sql.append(')');
        db.execSQL(sql.toString());
    } else {
        throw new IllegalStateException(clazz + " not DatabaseTable Annotation");
    }
}
 
Example 6
Source File: ReflectionUtils.java    From sofa-ark with Apache License 2.0 5 votes vote down vote up
public static void makeAccessible(Field field) {
    if ((!Modifier.isPublic(field.getModifiers())
         || !Modifier.isPublic(field.getDeclaringClass().getModifiers()) || Modifier
        .isFinal(field.getModifiers())) && !field.isAccessible()) {
        field.setAccessible(true);
    }
}
 
Example 7
Source File: ReflectBeanUtils.java    From cms with Apache License 2.0 5 votes vote down vote up
public static Object mapToObject(Map<String,Object> map,Class<?> clszz) throws Exception{
	if (map == null || map.size() <= 0)  return null;
	
	Object obj = clszz.newInstance();
	//获取关联的所有类,本类以及所有父类
       boolean ret = true;
	
	Class<?> cls = obj.getClass();
	List<Class<?>> clazzs = new ArrayList<Class<?>>();
	while (ret) {
           clazzs.add(cls);
           cls = cls.getSuperclass();
           if (cls == null || cls == Object.class) break;
       }
	for (int i = 0; i < clazzs.size(); i++) {
           Field[] fields = clazzs.get(i).getDeclaredFields();
           for (Field field : fields) {
               int mod = field.getModifiers();
               if (Modifier.isStatic(mod) || Modifier.isFinal(mod)) {
                   continue;
               }
               //由字符串转换回对象对应的类型
               if (field != null) {
                   field.setAccessible(true);
                   field.set(obj, map.get(field.getName()));
               }
           }
       }
       return obj;
}
 
Example 8
Source File: MetricsUtil.java    From Battery-Metrics with MIT License 5 votes vote down vote up
public static boolean isNumericField(Field field) {
  Class fieldClass = field.getType();
  return !Modifier.isFinal(field.getModifiers())
      && (fieldClass.isAssignableFrom(int.class)
          || fieldClass.isAssignableFrom(float.class)
          || fieldClass.isAssignableFrom(long.class)
          || fieldClass.isAssignableFrom(double.class));
}
 
Example 9
Source File: POJOPropertiesCollector.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Method for collecting basic information on all fields found
 */
protected void _addFields(Map<String, POJOPropertyBuilder> props)
{
    final AnnotationIntrospector ai = _annotationIntrospector;
    /* 28-Mar-2013, tatu: For deserialization we may also want to remove
     *   final fields, as often they won't make very good mutators...
     *   (although, maybe surprisingly, JVM _can_ force setting of such fields!)
     */
    final boolean pruneFinalFields = !_forSerialization && !_config.isEnabled(MapperFeature.ALLOW_FINAL_FIELDS_AS_MUTATORS);
    final boolean transientAsIgnoral = _config.isEnabled(MapperFeature.PROPAGATE_TRANSIENT_MARKER);
    
    for (AnnotatedField f : _classDef.fields()) {
        String implName = ai.findImplicitPropertyName(f);
        // @JsonValue?
        if (Boolean.TRUE.equals(ai.hasAsValue(f))) {
            if (_jsonValueAccessors == null) {
                _jsonValueAccessors = new LinkedList<>();
            }
            _jsonValueAccessors.add(f);
            continue;
        }
        // @JsonAnySetter?
        if (Boolean.TRUE.equals(ai.hasAnySetter(f))) {
            if (_anySetterField == null) {
                _anySetterField = new LinkedList<AnnotatedMember>();
            }
            _anySetterField.add(f);
            continue;
        }
        if (implName == null) {
            implName = f.getName();
        }
        PropertyName pn;

        if (_forSerialization) {
            /* 18-Aug-2011, tatu: As per existing unit tests, we should only
             *   use serialization annotation (@JsonSerialize) when serializing
             *   fields, and similarly for deserialize-only annotations... so
             *   no fallbacks in this particular case.
             */
            pn = ai.findNameForSerialization(f);
        } else {
            pn = ai.findNameForDeserialization(f);
        }
        boolean hasName = (pn != null);
        boolean nameExplicit = hasName;

        if (nameExplicit && pn.isEmpty()) { // empty String meaning "use default name", here just means "same as field name"
            pn = _propNameFromSimple(implName);
            nameExplicit = false;
        }
        // having explicit name means that field is visible; otherwise need to check the rules
        boolean visible = (pn != null);
        if (!visible) {
            visible = _visibilityChecker.isFieldVisible(f);
        }
        // and finally, may also have explicit ignoral
        boolean ignored = ai.hasIgnoreMarker(f);

        // 13-May-2015, tatu: Moved from earlier place (AnnotatedClass) in 2.6
        if (f.isTransient()) {
            // 20-May-2016, tatu: as per [databind#1184] explicit annotation should override
            //    "default" `transient`
            if (!hasName) {
                visible = false;
                if (transientAsIgnoral) {
                    ignored = true;
                }
            }
        }
        /* [databind#190]: this is the place to prune final fields, if they are not
         *  to be used as mutators. Must verify they are not explicitly included.
         *  Also: if 'ignored' is set, need to included until a later point, to
         *  avoid losing ignoral information.
         */
        if (pruneFinalFields && (pn == null) && !ignored
                && Modifier.isFinal(f.getModifiers())) {
            continue;
        }
        _property(props, implName).addField(f, pn, nameExplicit, visible, ignored);
    }
}
 
Example 10
Source File: StringUtils.java    From arthas with Apache License 2.0 4 votes vote down vote up
/**
 * 翻译Modifier值
 *
 * @param mod modifier
 * @return 翻译值
 */
public static String modifier(int mod, char splitter) {
    StringBuilder sb = new StringBuilder();
    if (Modifier.isAbstract(mod)) {
        sb.append("abstract").append(splitter);
    }
    if (Modifier.isFinal(mod)) {
        sb.append("final").append(splitter);
    }
    if (Modifier.isInterface(mod)) {
        sb.append("interface").append(splitter);
    }
    if (Modifier.isNative(mod)) {
        sb.append("native").append(splitter);
    }
    if (Modifier.isPrivate(mod)) {
        sb.append("private").append(splitter);
    }
    if (Modifier.isProtected(mod)) {
        sb.append("protected").append(splitter);
    }
    if (Modifier.isPublic(mod)) {
        sb.append("public").append(splitter);
    }
    if (Modifier.isStatic(mod)) {
        sb.append("static").append(splitter);
    }
    if (Modifier.isStrict(mod)) {
        sb.append("strict").append(splitter);
    }
    if (Modifier.isSynchronized(mod)) {
        sb.append("synchronized").append(splitter);
    }
    if (Modifier.isTransient(mod)) {
        sb.append("transient").append(splitter);
    }
    if (Modifier.isVolatile(mod)) {
        sb.append("volatile").append(splitter);
    }
    if (sb.length() > 0) {
        sb.deleteCharAt(sb.length() - 1);
    }
    return sb.toString();
}
 
Example 11
Source File: TestFinalGetters.java    From reladomo with Apache License 2.0 4 votes vote down vote up
private static boolean isFinal(Class aClass, String method) throws NoSuchMethodException
{
    return Modifier.isFinal(aClass.getDeclaredMethod(method).getModifiers());
}
 
Example 12
Source File: MemberName.java    From JDKSourceCode1.8 with MIT License 4 votes vote down vote up
/** Utility method to query the modifier flags of this member. */
public boolean isFinal() {
    return Modifier.isFinal(flags);
}
 
Example 13
Source File: Resources.java    From jdk8u-jdk with GNU General Public License v2.0 4 votes vote down vote up
private static boolean isWritableField(Field field) {
    int modifiers = field.getModifiers();
    return Modifier.isPublic(modifiers) && Modifier.isStatic(modifiers)
            && !Modifier.isFinal(modifiers);
}
 
Example 14
Source File: ProgramElementDocImpl.java    From openjdk-8-source with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Return true if this program element is final
 */
public boolean isFinal() {
    int modifiers = getModifiers();
    return Modifier.isFinal(modifiers);
}
 
Example 15
Source File: VOConverterGenerator.java    From development with Apache License 2.0 4 votes vote down vote up
/**
 * Getting list of VO properties.
 * 
 * @param vOName
 *            Name of VO.
 * @return List of VO properties.
 */
public List<VOPropertyDescription> getVOProperties(String vOName) {
    String fullClassName = VO_PACKAGE_NAME + "." + vOName;

    ArrayList<VOPropertyDescription> voList = new ArrayList<VOPropertyDescription>();

    try {
        Class<?> cl = Class.forName(fullClassName);

        Field fld[] = cl.getDeclaredFields();

        // System.out.println("Superclass : " + superClassName);
        if (isSuperClassOfTypeBaseVO(cl)) {

            // add key and version from BaseVO
            VOPropertyDescription descrBaseKey = new VOPropertyDescription();
            descrBaseKey.setName("key");
            descrBaseKey.setGenericType("long");
            descrBaseKey.setType("long");
            descrBaseKey.setTypeParameter("");
            descrBaseKey.setTypeParameterWithoutPackage("");
            voList.add(descrBaseKey);

            VOPropertyDescription descrBaseVersion = new VOPropertyDescription();
            descrBaseVersion.setName("version");
            descrBaseVersion.setGenericType("int");
            descrBaseVersion.setType("int");
            descrBaseVersion.setTypeParameter("");
            descrBaseVersion.setTypeParameterWithoutPackage("");
            voList.add(descrBaseVersion);
        }
        // --

        for (int i = 0; i < fld.length; i++) {
            VOPropertyDescription descr = new VOPropertyDescription();

            int modifiers = fld[i].getModifiers();
            boolean constProp = false;
            if (Modifier.isFinal(modifiers) && Modifier.isStatic(modifiers)) {
                constProp = true;
            }

            String genericType = fld[i].getGenericType().toString();
            String[] inputs = genericType.split("\\<|\\>| ");

            String propertyName = fld[i].getName();

            if (!propertyName.equals("serialVersionUID") && !constProp) {
                descr.setName(propertyName);
                descr.setGenericType(genericType);
                descr.setType(inputs[0]);
                descr.setEnumType(fld[i].getType().isEnum());
                if (inputs.length > 1) {
                    descr.setTypeParameter(inputs[1]);
                    String[] parts = inputs[1].split("\\.");
                    descr.setTypeParameterWithoutPackage(parts[parts.length - 1]);
                } else {
                    descr.setTypeParameter("");
                    descr.setTypeParameterWithoutPackage("");
                }

                voList.add(descr);

                // System.out.println(descr.toString());

                if (descr.getType().equals("java.util.List")) {
                    if (!setOfVOLists.contains(descr
                            .getTypeParameterWithoutPackage())) {
                        setOfVOLists.add(descr
                                .getTypeParameterWithoutPackage());
                    }
                }
            }
        }
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }

    return voList;
}
 
Example 16
Source File: ClassInfo.java    From PATDroid with Apache License 2.0 4 votes vote down vote up
/**
 * @return if the class is final
 */
public boolean isFinal() {
    return Modifier.isFinal(mutableDetail.accessFlags);
}
 
Example 17
Source File: ServiceContextData.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 4 votes vote down vote up
public ServiceContextData( Class cls )
{
    if (ORB.ORBInitDebug)
        dprint( "ServiceContextData constructor called for class " + cls ) ;

    scClass = cls ;

    try {
        if (ORB.ORBInitDebug)
            dprint( "Finding constructor for " + cls ) ;

        // Find the appropriate constructor in cls
        Class[] args = new Class[2] ;
        args[0] = InputStream.class ;
        args[1] = GIOPVersion.class;
        try {
            scConstructor = cls.getConstructor( args ) ;
        } catch (NoSuchMethodException nsme) {
            throwBadParam( "Class does not have an InputStream constructor", nsme ) ;
        }

        if (ORB.ORBInitDebug)
            dprint( "Finding SERVICE_CONTEXT_ID field in " + cls ) ;

        // get the ID from the public static final int SERVICE_CONTEXT_ID
        Field fld = null ;
        try {
            fld = cls.getField( "SERVICE_CONTEXT_ID" ) ;
        } catch (NoSuchFieldException nsfe) {
            throwBadParam( "Class does not have a SERVICE_CONTEXT_ID member", nsfe ) ;
        } catch (SecurityException se) {
            throwBadParam( "Could not access SERVICE_CONTEXT_ID member", se ) ;
        }

        if (ORB.ORBInitDebug)
            dprint( "Checking modifiers of SERVICE_CONTEXT_ID field in " + cls ) ;

        int mod = fld.getModifiers() ;
        if (!Modifier.isPublic(mod) || !Modifier.isStatic(mod) ||
            !Modifier.isFinal(mod) )
            throwBadParam( "SERVICE_CONTEXT_ID field is not public static final", null ) ;

        if (ORB.ORBInitDebug)
            dprint( "Getting value of SERVICE_CONTEXT_ID in " + cls ) ;

        try {
            scId = fld.getInt( null ) ;
        } catch (IllegalArgumentException iae) {
            throwBadParam( "SERVICE_CONTEXT_ID not convertible to int", iae ) ;
        } catch (IllegalAccessException iae2) {
            throwBadParam( "Could not access value of SERVICE_CONTEXT_ID", iae2 ) ;
        }
    } catch (BAD_PARAM nssc) {
        if (ORB.ORBInitDebug)
            dprint( "Exception in ServiceContextData constructor: " + nssc ) ;
        throw nssc ;
    } catch (Throwable thr) {
        if (ORB.ORBInitDebug)
            dprint( "Unexpected Exception in ServiceContextData constructor: " +
                    thr ) ;
    }

    if (ORB.ORBInitDebug)
        dprint( "ServiceContextData constructor completed" ) ;
}
 
Example 18
Source File: Invokable.java    From codebuff with BSD 2-Clause "Simplified" License 4 votes vote down vote up
@Override
public final boolean isOverridable() {
  return !(isFinal() || isPrivate() || isStatic()
           || Modifier.isFinal(getDeclaringClass().getModifiers()));
}
 
Example 19
Source File: JavaAdapterBytecodeGenerator.java    From openjdk-jdk8u with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Gathers methods that can be implemented or overridden from the specified type into this factory's
 * {@link #methodInfos} set. It will add all non-final, non-static methods that are either public or protected from
 * the type if the type itself is public. If the type is a class, the method will recursively invoke itself for its
 * superclass and the interfaces it implements, and add further methods that were not directly declared on the
 * class.
 * @param type the type defining the methods.
 */
private void gatherMethods(final Class<?> type) throws AdaptationException {
    if (Modifier.isPublic(type.getModifiers())) {
        final Method[] typeMethods = type.isInterface() ? type.getMethods() : type.getDeclaredMethods();

        for (final Method typeMethod: typeMethods) {
            final String name = typeMethod.getName();
            if(name.startsWith(SUPER_PREFIX)) {
                continue;
            }
            final int m = typeMethod.getModifiers();
            if (Modifier.isStatic(m)) {
                continue;
            }
            if (Modifier.isPublic(m) || Modifier.isProtected(m)) {
                // Is it a "finalize()"?
                if(name.equals("finalize") && typeMethod.getParameterCount() == 0) {
                    if(type != Object.class) {
                        hasExplicitFinalizer = true;
                        if(Modifier.isFinal(m)) {
                            // Must be able to override an explicit finalizer
                            throw new AdaptationException(Outcome.ERROR_FINAL_FINALIZER, type.getCanonicalName());
                        }
                    }
                    continue;
                }

                final MethodInfo mi = new MethodInfo(typeMethod);
                if (Modifier.isFinal(m) || isCallerSensitive(typeMethod)) {
                    finalMethods.add(mi);
                } else if (!finalMethods.contains(mi) && methodInfos.add(mi)) {
                    if (Modifier.isAbstract(m)) {
                        abstractMethodNames.add(mi.getName());
                    }
                    mi.setIsCanonical(this);
                }
            }
        }
    }
    // If the type is a class, visit its superclasses and declared interfaces. If it's an interface, we're done.
    // Needing to invoke the method recursively for a non-interface Class object is the consequence of needing to
    // see all declared protected methods, and Class.getDeclaredMethods() doesn't provide those declared in a
    // superclass. For interfaces, we used Class.getMethods(), as we're only interested in public ones there, and
    // getMethods() does provide those declared in a superinterface.
    if (!type.isInterface()) {
        final Class<?> superType = type.getSuperclass();
        if (superType != null) {
            gatherMethods(superType);
        }
        for (final Class<?> itf: type.getInterfaces()) {
            gatherMethods(itf);
        }
    }
}
 
Example 20
Source File: Reflections.java    From keycloak with Apache License 2.0 2 votes vote down vote up
/**
 * Checks if class is final
 *
 * @param clazz The class to check
 *
 * @return True if final, false otherwise
 */
public static boolean isFinal(Class<?> clazz) {
    return Modifier.isFinal(clazz.getModifiers());
}