Example usage for java.lang Class getDeclaredFields

List of usage examples for java.lang Class getDeclaredFields

Introduction

In this page you can find the example usage for java.lang Class getDeclaredFields.

Prototype

@CallerSensitive
public Field[] getDeclaredFields() throws SecurityException 

Source Link

Document

Returns an array of Field objects reflecting all the fields declared by the class or interface represented by this Class object.

Usage

From source file:net.minecraftforge.common.config.ConfigManager.java

private static void sync(Configuration cfg, Class<?> cls, String modid, String category, boolean loading,
        Object instance) {/*from   w  ww .  j  a  v  a2 s.c  om*/
    for (Field f : cls.getDeclaredFields()) {
        if (!Modifier.isPublic(f.getModifiers()))
            continue;

        //Only the root class may have static fields. Otherwise category tree nodes of the same type would share the
        //contained value messing up the sync
        if (Modifier.isStatic(f.getModifiers()) != (instance == null))
            continue;

        if (f.isAnnotationPresent(Config.Ignore.class))
            continue;

        String comment = null;
        Comment ca = f.getAnnotation(Comment.class);
        if (ca != null)
            comment = NEW_LINE.join(ca.value());

        String langKey = modid + "." + (category.isEmpty() ? "" : category + Configuration.CATEGORY_SPLITTER)
                + f.getName().toLowerCase(Locale.ENGLISH);
        LangKey la = f.getAnnotation(LangKey.class);
        if (la != null)
            langKey = la.value();

        boolean requiresMcRestart = f.isAnnotationPresent(Config.RequiresMcRestart.class);
        boolean requiresWorldRestart = f.isAnnotationPresent(Config.RequiresWorldRestart.class);

        if (FieldWrapper.hasWrapperFor(f)) //Wrappers exist for primitives, enums, maps and arrays
        {
            if (Strings.isNullOrEmpty(category))
                throw new RuntimeException(
                        "An empty category may not contain anything but objects representing categories!");
            try {
                IFieldWrapper wrapper = FieldWrapper.get(instance, f, category);
                ITypeAdapter adapt = wrapper.getTypeAdapter();
                Property.Type propType = adapt.getType();

                for (String key : wrapper.getKeys()) //Iterate the fully qualified property names the field provides
                {
                    String suffix = StringUtils.replaceOnce(key,
                            wrapper.getCategory() + Configuration.CATEGORY_SPLITTER, "");

                    boolean existed = exists(cfg, wrapper.getCategory(), suffix);
                    if (!existed || loading) //Creates keys in category specified by the wrapper if new ones are programaticaly added
                    {
                        Property property = property(cfg, wrapper.getCategory(), suffix, propType,
                                adapt.isArrayAdapter());

                        adapt.setDefaultValue(property, wrapper.getValue(key));
                        if (!existed)
                            adapt.setValue(property, wrapper.getValue(key));
                        else
                            wrapper.setValue(key, adapt.getValue(property));
                    } else //If the key is not new, sync according to shouldReadFromVar()
                    {
                        Property property = property(cfg, wrapper.getCategory(), suffix, propType,
                                adapt.isArrayAdapter());
                        Object propVal = adapt.getValue(property);
                        Object mapVal = wrapper.getValue(key);
                        if (shouldReadFromVar(property, propVal, mapVal))
                            adapt.setValue(property, mapVal);
                        else
                            wrapper.setValue(key, propVal);
                    }
                }

                ConfigCategory confCat = cfg.getCategory(wrapper.getCategory());

                for (Property property : confCat.getOrderedValues()) //Iterate the properties to check for new data from the config side
                {
                    String key = confCat.getQualifiedName() + Configuration.CATEGORY_SPLITTER
                            + property.getName();
                    if (!wrapper.handlesKey(key))
                        continue;

                    if (loading || !wrapper.hasKey(key)) {
                        Object value = wrapper.getTypeAdapter().getValue(property);
                        wrapper.setValue(key, value);
                    }
                }

                if (loading)
                    wrapper.setupConfiguration(cfg, comment, langKey, requiresMcRestart, requiresWorldRestart);

            } catch (Exception e) {
                String format = "Error syncing field '%s' of class '%s'!";
                String error = String.format(format, f.getName(), cls.getName());
                throw new RuntimeException(error, e);
            }
        } else if (f.getType().getSuperclass() != null && f.getType().getSuperclass().equals(Object.class)) { //If the field extends Object directly, descend the object tree and access the objects members
            Object newInstance = null;
            try {
                newInstance = f.get(instance);
            } catch (IllegalAccessException e) {
                throw new RuntimeException(e);
            }

            //Setup the sub category with its respective name, comment, language key, etc.
            String sub = (category.isEmpty() ? "" : category + Configuration.CATEGORY_SPLITTER)
                    + getName(f).toLowerCase(Locale.ENGLISH);
            ConfigCategory confCat = cfg.getCategory(sub);
            confCat.setComment(comment);
            confCat.setLanguageKey(langKey);
            confCat.setRequiresMcRestart(requiresMcRestart);
            confCat.setRequiresWorldRestart(requiresWorldRestart);

            sync(cfg, f.getType(), modid, sub, loading, newInstance);
        } else {
            String format = "Can't handle field '%s' of class '%s': Unknown type.";
            String error = String.format(format, f.getName(), cls.getCanonicalName());
            throw new RuntimeException(error);
        }
    }
}

From source file:gumga.framework.presentation.api.CSVGeneratorAPI.java

public static List<Field> getAllAtributes(Class clazz) {
    List<Field> fields = new ArrayList<>();
    Class superClass = clazz.getSuperclass();
    if (superClass != null && !superClass.equals(Object.class)) {
        fields.addAll(getAllAtributes(clazz.getSuperclass()));
    }/*  w  w w.j ava 2s.  co  m*/
    for (Field f : clazz.getDeclaredFields()) {
        if (!Modifier.isStatic(f.getModifiers())) {
            fields.add(f);
        }
    }
    return fields;
}

From source file:cn.afterturn.easypoi.util.PoiPublicUtil.java

/**
 * ?class /*from  w  w w  .j  a  v  a2 s . c om*/
 *
 * @param clazz
 * @return
 */
public static Field[] getClassFields(Class<?> clazz) {
    List<Field> list = new ArrayList<Field>();
    Field[] fields;
    do {
        fields = clazz.getDeclaredFields();
        for (int i = 0; i < fields.length; i++) {
            list.add(fields[i]);
        }
        clazz = clazz.getSuperclass();
    } while (clazz != Object.class && clazz != null);
    return list.toArray(fields);
}

From source file:org.fusesource.meshkeeper.util.internal.IntrospectionSupport.java

private static void addFields(Object target, Class<?> startClass, Class<?> stopClass,
        LinkedHashMap<String, Object> map) {

    if (startClass != stopClass) {
        addFields(target, startClass.getSuperclass(), stopClass, map);
    }//from   ww w.  j  av  a  2s .c  o m

    Field[] fields = startClass.getDeclaredFields();
    for (int i = 0; i < fields.length; i++) {
        Field field = fields[i];
        if (Modifier.isStatic(field.getModifiers()) || Modifier.isTransient(field.getModifiers())
                || Modifier.isPrivate(field.getModifiers())) {
            continue;
        }

        try {
            field.setAccessible(true);
            Object o = field.get(target);
            if (o != null && o.getClass().isArray()) {
                try {
                    o = Arrays.asList((Object[]) o);
                } catch (Throwable e) {
                }
            }
            map.put(field.getName(), o);
        } catch (Throwable e) {
            e.printStackTrace();
        }
    }

}

From source file:com.beetle.framework.util.ObjectUtil.java

/**
 * ???//from ww  w .j a va2  s . c  o  m
 * 
 * @param target
 * @param field
 * @param value
 */
public final static void setFieldValue(Object target, String field, Object value) {
    try {
        Class<?> obj = target.getClass();
        Field[] fields = obj.getDeclaredFields();
        for (int i = 0; i < fields.length; i++) {
            fields[i].setAccessible(true);
            if (field.equals(fields[i].getName())) {
                fields[i].set(target, value);
                break;
            }
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:ReflectUtil.java

/**
 * Fetches all fields of all access types from the supplied class and super
 * classes. Fieldss that have been overridden in the inheritance hierarchy are
 * only returned once, using the instance lowest down the hierarchy.
 *
 * @param clazz the class to inspect/*from   ww w . ja va  2  s . c  o  m*/
 * @return a collection of fields
 */
public static Collection<Field> getFields(Class<?> clazz) {
    Map<String, Field> fields = new HashMap<String, Field>();
    while (clazz != null) {
        for (Field field : clazz.getDeclaredFields()) {
            if (!fields.containsKey(field.getName())) {
                fields.put(field.getName(), field);
            }
        }

        clazz = clazz.getSuperclass();
    }

    return fields.values();
}

From source file:com.l2jfree.util.Introspection.java

private static boolean writeFields(Class<?> c, Object accessor, StringBuilder dest, String eol, boolean init) {
    if (c == null)
        throw new IllegalArgumentException("No class specified.");
    else if (!c.isInstance(accessor))
        throw new IllegalArgumentException(accessor + " is not a " + c.getCanonicalName());
    for (Field f : c.getDeclaredFields()) {
        int mod = f.getModifiers();
        if (Modifier.isStatic(mod))
            continue;
        if (init)
            init = false;/*  w w w  .  j  av  a2  s.  com*/
        else if (eol == null)
            dest.append(", ");
        String fieldName = null;
        final Column column = f.getAnnotation(Column.class);
        if (column != null)
            fieldName = column.name();
        if (StringUtils.isEmpty(fieldName))
            fieldName = f.getName();
        dest.append(fieldName);
        dest.append(" = ");
        try {
            f.setAccessible(true);
            Object val = f.get(accessor);
            if (accessor == val)
                dest.append("this");
            else
                deepToString(val, dest, null);
        } catch (Exception e) {
            dest.append("???");
        } finally {
            try {
                f.setAccessible(false);
            } catch (Exception e) {
                // ignore
            }
        }
        if (eol != null)
            dest.append(eol);
    }
    return !init;
}

From source file:com.impetus.ankush.common.utils.JsonMapperUtil.java

/**
 * Object from map./* w ww  .j  a va2  s.c om*/
 * 
 * @param <S>
 *            the generic type
 * @param values
 *            the values
 * @param targetClass
 *            the target class
 * @return the s
 * @throws IllegalArgumentException
 *             the illegal argument exception
 * @throws IllegalAccessException
 *             the illegal access exception
 * @throws InstantiationException
 *             the instantiation exception
 * @throws InvocationTargetException
 *             the invocation target exception
 * @throws Exception
 *             the exception
 */
public static <S> S objectFromMap(Map<String, Object> values, Class<S> targetClass)
        throws IllegalArgumentException, IllegalAccessException, InstantiationException,
        InvocationTargetException, Exception {
    // Creating target class object.
    S mainObject = targetClass.newInstance();

    // Getting fields of the class.
    Field[] fields = targetClass.getDeclaredFields();
    Map<String, Field> fieldMap = new HashMap<String, Field>();

    for (Field field : fields) {
        // Putting fields in fieldMap
        fieldMap.put(field.getName(), field);
    }

    // Iterating over the key set in value map.
    for (String mainKey : values.keySet()) {
        if (values.get(mainKey) instanceof LinkedHashMap) {
            // Creating target object type.
            if (fieldMap.get(mainKey) == null) {
                continue;
            }
            Object subObject = fieldMap.get(mainKey).getType().newInstance();

            // Casting to map.
            Map subValues = (Map) values.get(mainKey);

            // Iterating over the map keys.
            for (Object subKey : subValues.keySet()) {
                BeanUtils.setProperty(subObject, (String) subKey, subValues.get(subKey));
            }

            // setting the sub object in bean main object.
            BeanUtils.setProperty(mainObject, mainKey, subObject);
        } else {
            // setting the value in bean main object.
            BeanUtils.setProperty(mainObject, mainKey, values.get(mainKey));
        }
    }
    return mainObject;
}

From source file:com.github.gekoh.yagen.util.MappingUtils.java

public static Set<Field> getFielsWith(Class<? extends Annotation> a, Class clazz) {
    Set<Field> fields = new HashSet<Field>();

    for (Field field : clazz.getDeclaredFields()) {
        if (field.isAnnotationPresent(a)) {
            fields.add(field);//from  ww w .  j a va2  s  .c o m
        }
    }

    return fields;
}

From source file:com.us.reflect.ClassFinder.java

/**
 *  before/*from   w  w w  .j  av a  2s. c  o  m*/
 * @param invocation
 */
public static void beforeAction(ActionInvocation invc, String actionPath) throws Exception {
    ActionInvocation invocation = (ActionInvocation) invc;
    final ActionProxy proxy = invocation.getProxy();
    Class<?> classFromPath = findClass(actionPath);// ?Class
    Class<?> targetClass = classFromPath == null ? proxy.getAction().getClass() : classFromPath;
    String methodName = findMethodName(actionPath);// ??? checkExist(sessionKey)
    String[] paramers = findParameters(actionPath);
    Class<?>[] paramersType = findParameterTypes(targetClass, paramers);
    Method method = targetClass.getDeclaredMethod(methodName, paramersType);
    Object runner = targetClass.newInstance();
    Field[] allFiled = targetClass.getDeclaredFields();
    for (Field field : allFiled) {
        String beanName = field.getName();
        Object bean = DaoHelper.getBeanById(beanName);
        if (bean != null) {
            BeanUtils.setProperty(runner, beanName, bean);
        }
    }
    method.invoke(runner, getRuntimeArgs(invocation, paramers));
}