Example usage for java.lang.reflect Field isSynthetic

List of usage examples for java.lang.reflect Field isSynthetic

Introduction

In this page you can find the example usage for java.lang.reflect Field isSynthetic.

Prototype

public boolean isSynthetic() 

Source Link

Document

Returns true if this field is a synthetic field; returns false otherwise.

Usage

From source file:org.soyatec.windowsazure.internal.util.xml.AtomUtil.java

private static String convertToXml(String tableName, ITableServiceEntity entity) {
    StringBuilder sb = new StringBuilder();
    sb.append(MessageFormat.format("<content type=\"{0}\">", TableStorageConstants.ApplicationXml));
    sb.append("<m:properties>");
    sb.append(// w  ww .j  a  v  a2 s  .c  o  m
            MessageFormat.format("<d:PartitionKey>{0}</d:PartitionKey>", escapeXml(entity.getPartitionKey())));
    sb.append(MessageFormat.format("<d:RowKey>{0}</d:RowKey>", escapeXml(entity.getRowKey())));

    List<?> ignoreFields = Arrays.asList(new String[] { "rowKey", "partitionKey", "timestamp" });
    Class<?> clazz = entity.getClass();
    Field[] fields = clazz.getDeclaredFields();

    for (Field f : fields) {
        String name = f.getName();
        if (ignoreFields.contains(name)) {
            continue;
        }
        if (Modifier.isTransient(f.getModifiers()) || f.isSynthetic()) {
            continue;
        }
        sb.append(convertToXml(f, entity));
    }
    List<ICloudTableColumn> properties = entity.getValues();
    if (properties != null) {
        for (ICloudTableColumn key : properties) {
            sb.append(MessageFormat.format("<d:{0}>{1}</d:{0}>", key.getName(), escapeXml(key.getValue())));
        }
    }

    sb.append("<d:Timestamp m:type=\"Edm.DateTime\">" + Utilities.formatTimeStamp(entity.getTimestamp())
            + "</d:Timestamp>");
    sb.append("</m:properties></content>");
    return sb.toString();
}

From source file:wwutil.sys.ReflectUtil.java

private static List<Field> getAllFields(Class clazz, List<Field> list) {
    for (Field field : clazz.getDeclaredFields()) {
        // Filter out compiler synthesized fields and static fields.
        if (!field.isSynthetic() && !Modifier.isStatic(field.getModifiers()))
            list.add(field);/*from  w w  w.  j  ava  2s .c  om*/
    }
    Class superClazz = clazz.getSuperclass();
    if (superClazz != null)
        getAllFields(superClazz, list);
    return list;
}

From source file:org.kuali.rice.krad.uif.util.CloneUtils.java

public static Field[] getFields(Class<?> c, boolean includeStatic, boolean includeTransient) {
    String cacheKey = c.getName() + ":" + includeStatic;
    Field[] array = fieldCache.get(cacheKey);

    if (array == null) {
        ArrayList<Field> fields = new ArrayList<Field>();

        List<Class<?>> classes = getClassHierarchy(c, false);

        // Reverse order so we make sure we maintain consistent order
        Collections.reverse(classes);

        for (Class<?> clazz : classes) {
            Field[] allFields = clazz.getDeclaredFields();
            for (Field f : allFields) {
                if ((!includeTransient) && ((f.getModifiers() & Modifier.TRANSIENT) == Modifier.TRANSIENT)) {
                    continue;
                } else if (f.isSynthetic()) {
                    // Synthetic fields are bad!!!
                    continue;
                }/*w  w w  .ja  va 2 s .  c om*/
                boolean isStatic = (f.getModifiers() & Modifier.STATIC) == Modifier.STATIC;
                if ((isStatic) && (!includeStatic)) {
                    continue;
                }
                if (f.getName().equalsIgnoreCase("serialVersionUID")) {
                    continue;
                }
                f.setAccessible(true);
                fields.add(f);
            }
        }

        array = fields.toArray(new Field[fields.size()]);
        fieldCache.put(cacheKey, array);
    }
    return array;
}

From source file:com.impetus.kundera.utils.KunderaCoreUtils.java

public static int countNonSyntheticFields(Class<?> clazz) {
    int count = 0;
    for (Field f : clazz.getDeclaredFields()) {
        if (!f.isSynthetic() || !ReflectUtils.isTransientOrStatic(f)) {
            count++;/*from   www  .j a  va2 s  .c  om*/
        }
    }

    return count;
}

From source file:ml.shifu.shifu.container.meta.MetaFactory.java

/**
 * Iterate each property of Object, get the value and validate
 * //w w  w  . j ava 2 s .c  om
 * @param isGridSearch
 *            - if grid search, ignore validation in train#params as they are set all as list
 * @param ptag
 *            - the prefix of key to search @MetaItem
 * @param obj
 *            - the object to validate
 * @return ValidateResult
 *         If all items are OK, the ValidateResult.status will be true;
 *         Or the ValidateResult.status will be false, ValidateResult.causes will contain the reasons
 * @throws Exception
 *             any exception in validaiton
 */
public static ValidateResult iterateCheck(boolean isGridSearch, String ptag, Object obj) throws Exception {
    ValidateResult result = new ValidateResult(true);
    if (obj == null) {
        return result;
    }

    Class<?> cls = obj.getClass();
    Field[] fields = cls.getDeclaredFields();

    Class<?> parentCls = cls.getSuperclass();
    if (!parentCls.equals(Object.class)) {
        Field[] pfs = parentCls.getDeclaredFields();
        fields = (Field[]) ArrayUtils.addAll(fields, pfs);
    }

    for (Field field : fields) {
        if (!field.isSynthetic() && !Modifier.isStatic(field.getModifiers()) && !isJsonIngoreField(field)) {
            Method method = cls.getMethod("get" + getMethodName(field.getName()));
            Object value = method.invoke(obj);

            encapsulateResult(result,
                    validate(isGridSearch, ptag + ITEM_KEY_SEPERATOR + field.getName(), value));
        }
    }

    return result;
}

From source file:org.diorite.cfg.system.TemplateCreator.java

/**
 * Get template for given class.//from   w  ww .j  av  a 2  s.  c om
 *
 * @param clazz    class to get template.
 * @param create   if template should be created if it don't exisit yet.
 * @param cache    if template should be saved to memory if created.
 * @param recreate if template should be force re-created even if it exisit.
 * @param <T>      Type of template class
 *
 * @return template class or null.
 */
@SuppressWarnings("unchecked")
public static <T> Template<T> getTemplate(final Class<T> clazz, final boolean create, final boolean cache,
        final boolean recreate) {
    if (!recreate) {
        final Template<T> template = (Template<T>) templateMap.get(clazz);
        if (template != null) {
            return template;
        }
        if (!create) {
            return null;
        }
    }
    Supplier<T> def = null;
    {
        final CfgDelegateDefault annotation = clazz.getAnnotation(CfgDelegateDefault.class);
        if (annotation != null) {
            final String path = annotation.value();
            final Supplier<Object> basicDelegate = ConfigField.getBasicDelegate(path);
            if (basicDelegate != null) {
                def = (Supplier<T>) basicDelegate;
            } else if (path.equalsIgnoreCase("{new}")) {
                final ConstructorInvoker constructor = DioriteReflectionUtils.getConstructor(clazz);
                def = () -> (T) constructor.invoke();
            } else {
                final int sepIndex = path.indexOf("::");
                final Class<?> targetClass;
                final String methodName;
                if (sepIndex == -1) {
                    targetClass = clazz;
                    methodName = path;
                } else {
                    try {
                        Class<?> tmpClass = DioriteReflectionUtils
                                .tryGetCanonicalClass(path.substring(0, sepIndex));
                        if (tmpClass == null) {
                            tmpClass = DioriteReflectionUtils.tryGetCanonicalClass(
                                    clazz.getPackage().getName() + "." + path.substring(0, sepIndex));
                            if (tmpClass == null) {
                                tmpClass = DioriteReflectionUtils.getNestedClass(clazz,
                                        path.substring(0, sepIndex));
                            }
                        }
                        targetClass = tmpClass;
                    } catch (final Exception e) {
                        throw new RuntimeException("Can't find class for: " + path, e);
                    }
                    methodName = path.substring(sepIndex + 2);
                }
                if (targetClass == null) {
                    throw new RuntimeException("Can't find class for delegate: " + path);
                }
                final MethodInvoker methodInvoker = DioriteReflectionUtils.getMethod(targetClass, methodName,
                        false);
                if (methodInvoker == null) {
                    final ReflectGetter<Object> reflectGetter = DioriteReflectionUtils
                            .getReflectGetter(methodName, targetClass);
                    def = () -> (T) reflectGetter.get(null);
                } else {
                    def = () -> (T) methodInvoker.invoke(null);
                }
            }
        }
    }

    final boolean allFields;
    //        final boolean superFields;
    final boolean ignoreTransient;
    final String name;
    final String header;
    final String footer;
    final Collection<String> excludedFields = new HashSet<>(5);
    {
        final CfgClass cfgInfo = clazz.getAnnotation(CfgClass.class);
        if (cfgInfo != null) {
            allFields = cfgInfo.allFields();
            //                superFields = cfgInfo.superFields();
            ignoreTransient = cfgInfo.ignoreTransient();
            name = (cfgInfo.name() != null) ? cfgInfo.name() : clazz.getSimpleName();
            Collections.addAll(excludedFields, cfgInfo.excludeFields());
        } else {
            allFields = true;
            //                superFields = true;
            ignoreTransient = true;
            name = clazz.getSimpleName();
        }
    }
    {
        final String[] comments = readComments(clazz);
        header = comments[0];
        footer = comments[1];
    }

    final Set<ConfigField> fields = new TreeSet<>();

    {
        final Collection<Class<?>> classes = new ArrayList<>(5);
        {
            Class<?> fieldsSrc = clazz;
            do {
                classes.add(fieldsSrc);
                fieldsSrc = fieldsSrc.getSuperclass();
                if (fieldsSrc == null) {
                    break;
                }
                final CfgClass cfgInfo = fieldsSrc.getAnnotation(CfgClass.class);
                if ((cfgInfo != null) && !cfgInfo.superFields()) {
                    break;
                }
            } while (!fieldsSrc.equals(Object.class));
        }

        for (final Class<?> fieldsSrc : classes) {
            int i = 0;
            for (final Field field : fieldsSrc.getDeclaredFields()) {
                if ((field.isAnnotationPresent(CfgField.class)
                        || (!field.isAnnotationPresent(CfgExclude.class) && !field.isSynthetic()
                                && (!ignoreTransient || !Modifier.isTransient(field.getModifiers()))
                                && (allFields || field.isAnnotationPresent(CfgField.class))
                                && !excludedFields.contains(field.getName())))
                        && !Modifier.isStatic(field.getModifiers())) {
                    fields.add(new ConfigField(field, i++));
                }
            }
        }
    }
    final Template<T> template = new BaseTemplate<>(name, clazz, header, footer, fields, clazz.getClassLoader(),
            def);
    if (cache) {
        templateMap.put(clazz, template);
        TemplateCreator.fields.put(clazz, template.getFieldsNameMap());
    }
    return template;
}

From source file:ml.shifu.shifu.container.meta.MetaFactory.java

/**
 * Validate the ModelConfig object, to make sure each item follow the constrain
 * //from   w ww. j  av a  2  s.  co  m
 * @param modelConfig
 *            - object to validate
 * @return ValidateResult
 *         If all items are OK, the ValidateResult.status will be true;
 *         Or the ValidateResult.status will be false, ValidateResult.causes will contain the reasons
 * @throws Exception
 *             any exception in validaiton
 */
public static ValidateResult validate(ModelConfig modelConfig) throws Exception {
    ValidateResult result = new ValidateResult(true);

    GridSearch gs = new GridSearch(modelConfig.getTrain().getParams(),
            modelConfig.getTrain().getGridConfigFileContent());

    Class<?> cls = modelConfig.getClass();
    Field[] fields = cls.getDeclaredFields();

    for (Field field : fields) {
        // skip log instance
        if (field.getName().equalsIgnoreCase("log") || field.getName().equalsIgnoreCase("logger")) {
            continue;
        }
        if (!field.isSynthetic()) {
            Method method = cls.getMethod("get" + getMethodName(field.getName()));
            Object value = method.invoke(modelConfig);

            if (value instanceof List) {
                List<?> objList = (List<?>) value;
                for (Object obj : objList) {
                    encapsulateResult(result, iterateCheck(gs.hasHyperParam(), field.getName(), obj));
                }
            } else {
                encapsulateResult(result, iterateCheck(gs.hasHyperParam(), field.getName(), value));
            }
        }
    }

    return result;
}

From source file:com.opengamma.financial.analytics.ircurve.CurveSpecificationBuilderConfiguration.java

private static List<String> getCurveSpecBuilderConfigurationNames() {
    final List<String> list = new ArrayList<>();
    for (final Field field : CurveSpecificationBuilderConfigurationFudgeBuilder.class.getDeclaredFields()) {
        if (Modifier.isStatic(field.getModifiers()) && field.isSynthetic() == false) {
            field.setAccessible(true);//from w w w.  j a va  2  s  .c  o  m
            try {
                list.add((String) field.get(null));
            } catch (final Exception ex) {
                // Ignore
            }
        }
    }
    Collections.sort(list, String.CASE_INSENSITIVE_ORDER);
    return ImmutableList.copyOf(list);
}

From source file:org.evosuite.instrumentation.mutation.ReplaceVariable.java

/**
 * This replicates TestUsageChecker.canUse but we need to avoid that
 * we try to access Properties.getTargetClassAndDontInitialise
 *
 * @param f/*from w ww. jav a2  s. c o  m*/
 * @return
 */
public static boolean canUse(Field f) {

    if (f.getDeclaringClass().equals(java.lang.Object.class))
        return false;// handled here to avoid printing reasons

    if (f.getDeclaringClass().equals(java.lang.Thread.class))
        return false;// handled here to avoid printing reasons

    if (f.isSynthetic()) {
        logger.debug("Skipping synthetic field " + f.getName());
        return false;
    }

    if (f.getName().startsWith("ajc$")) {
        logger.debug("Skipping AspectJ field " + f.getName());
        return false;
    }

    // in, out, err
    if (f.getDeclaringClass().equals(FileDescriptor.class)) {
        return false;
    }

    if (Modifier.isPublic(f.getModifiers())) {
        // It may still be the case that the field is defined in a non-visible superclass of the class
        // we already know we can use. In that case, the compiler would be fine with accessing the
        // field, but reflection would start complaining about IllegalAccess!
        // Therefore, we set the field accessible to be on the safe side
        TestClusterUtils.makeAccessible(f);
        return true;
    }

    // If default access rights, then check if this class is in the same package as the target class
    if (!Modifier.isPrivate(f.getModifiers())) {
        String packageName = ClassUtils.getPackageName(f.getDeclaringClass());

        if (packageName.equals(Properties.CLASS_PREFIX)) {
            TestClusterUtils.makeAccessible(f);
            return true;
        }
    }

    return false;
}

From source file:org.vulpe.commons.util.VulpeReflectUtil.java

/**
 * Returns list of fields in class or superclass.
 *
 * @param clazz//from  ww  w. j a v a  2  s .c o m
 * @return
 */
public static List<Field> getFields(final Class<?> clazz) {
    if (VulpeCacheHelper.getInstance().contains(clazz.getName().concat(".fields"))) {
        return VulpeCacheHelper.getInstance().get(clazz.getName().concat(".fields"));
    }
    Class<?> baseClass = clazz;
    final List<Field> list = new ArrayList<Field>();
    while (!baseClass.equals(Object.class)) {
        for (Field field : baseClass.getDeclaredFields()) {
            if (!Modifier.isStatic(field.getModifiers()) && !field.isSynthetic()) {
                list.add(field);
            }
        }
        baseClass = baseClass.getSuperclass();
    }
    VulpeCacheHelper.getInstance().put(clazz.getName().concat(".fields"), list);
    return list;
}