Example usage for java.lang Class getFields

List of usage examples for java.lang Class getFields

Introduction

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

Prototype

@CallerSensitive
public Field[] getFields() throws SecurityException 

Source Link

Document

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

Usage

From source file:net.servicefixture.util.ReflectionUtils.java

public static String getDefaultValue(Class type) {
    if (isEnumarationPatternClass(type)) {
        StringBuilder sb = new StringBuilder();
        Field[] fields = type.getFields();
        for (int i = 0; i < fields.length; i++) {
            if (type.equals(fields[i].getType()) && Modifier.isFinal(fields[i].getModifiers())
                    && Modifier.isPublic(fields[i].getModifiers())
                    && Modifier.isStatic(fields[i].getModifiers())) {
                try {
                    sb.append(fields[i].getName()).append(";");
                } catch (IllegalArgumentException e) {
                }// w  w w.  ja va2s . c  o m
            }
        }
        return sb.toString();
    } else if (type.isEnum()) {
        StringBuilder sb = new StringBuilder();
        try {
            Object[] array = (Object[]) type.getMethod("values").invoke(null);
            for (int i = 0; i < array.length; i++) {
                sb.append(array[i]).append(";");
            }
        } catch (Exception e) {
        }
        return sb.toString();

    } else if (Calendar.class.isAssignableFrom(type) || XMLGregorianCalendar.class.isAssignableFrom(type)) {
        return "${calendar.after(0)}";
    } else if (Date.class.isAssignableFrom(type)) {
        return "${date.after(0)}";
    } else if (Number.class.isAssignableFrom(type) || "long".equals(type.getName())
            || "int".equals(type.getName()) || "short".equals(type.getName()) || "float".equals(type.getName())
            || "double".equals(type.getName())) {
        return "0";
    } else if (String.class.equals(type)) {
        return "String";
    } else if (Boolean.class.equals(type) || "boolean".equals(type.getName())) {
        return "true";
    }

    return type.getName();
}

From source file:com.aw.swing.mvp.view.IPView.java

public static List<JComponent> getCmps(Object target) {
    //        logger.info("searching attributes " + target.getClass().getName());
    List components = new ArrayList();
    List<Field> forms = new ArrayList();
    Class cls = target.getClass();
    Field[] fields = cls.getFields();
    for (int i = 0; i < fields.length; i++) {
        if ((fields[i].getName().startsWith("txt") || fields[i].getName().startsWith("chk"))
                && !fields[i].getName().startsWith("chkSel")) {
            JComponent jComponemt;
            try {
                jComponemt = (JComponent) fields[i].get(target);
                if (jComponemt != null) {
                    jComponemt.putClientProperty("Field", fields[i]);
                    components.add(jComponemt);
                } else {
                    System.out.println("Null:<" + target.getClass() + ">- <" + fields[i].getName() + ">");
                }// w  ww .  java  2 s. co m
            } catch (IllegalAccessException e) {
                e.printStackTrace();
                throw new AWSystemException("Error getting teh value of:<" + fields[i].getName() + ">", e);
            }
        }
        if ((fields[i].getType().getSimpleName().startsWith("Frm"))) {
            forms.add(fields[i]);
        }
    }
    if (forms.size() > 0) {
        for (Field field : forms) {
            try {
                Object formToBeChecked = field.get(target);
                if (formToBeChecked != null) {
                    List formAttributes = getCmps(formToBeChecked);
                    if (formAttributes.size() > 0) {
                        components.addAll(formAttributes);
                    }
                } else {
                    throw new IllegalStateException("FRM NULL:" + field.getName());
                }
            } catch (IllegalAccessException e) {
                e.printStackTrace();
                throw new AWSystemException("Problems getting value for:<" + field.getName() + ">", e);
            }
        }
    }
    return components;
}

From source file:com.netflix.paas.config.base.ConfigurationProxyUtils.java

static void assignFieldValues(final Object obj, Class<?> type, DynamicPropertyFactory propertyFactory,
        AbstractConfiguration configuration) throws Exception {

    // Iterate through all fields and set initial value as well as set up dynamic properties
    // where necessary
    for (final Field field : type.getFields()) {
        Configuration c = field.getAnnotation(Configuration.class);
        if (c == null)
            continue;

        String defaultValue = field.get(obj).toString();
        String name = ConfigurationProxyUtils.getPropertyName(field, c);
        Supplier<?> supplier = ConfigurationProxyUtils.getStaticSupplier(field.getType(), name, defaultValue,
                configuration);//from   w  ww .j a va  2  s .c o m
        field.set(obj, supplier.get());

        if (field.getAnnotation(Dynamic.class) != null) {
            final PropertyWrapper<?> property;
            if (field.getType().isAssignableFrom(String.class)) {
                property = propertyFactory.getStringProperty(name, defaultValue);
            } else if (field.getType().isAssignableFrom(Integer.class)) {
                property = propertyFactory.getIntProperty(name,
                        defaultValue == null ? 0 : Integer.parseInt(defaultValue));
            } else if (field.getType().isAssignableFrom(Double.class)) {
                property = propertyFactory.getDoubleProperty(name,
                        defaultValue == null ? 0.0 : Double.parseDouble(defaultValue));
            } else if (field.getType().isAssignableFrom(Long.class)) {
                property = propertyFactory.getLongProperty(name,
                        defaultValue == null ? 0L : Long.parseLong(defaultValue));
            } else if (field.getType().isAssignableFrom(Boolean.class)) {
                property = propertyFactory.getBooleanProperty(name,
                        defaultValue == null ? false : Boolean.parseBoolean(defaultValue));
            } else {
                throw new RuntimeException("Unsupported type " + field.getType());
            }

            property.addCallback(new Runnable() {
                @Override
                public void run() {
                    try {
                        field.set(obj, property.getValue());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
        }
    }
}

From source file:org.springframework.test.context.junit4.SpringJUnit4ClassRunner.java

private static void ensureSpringRulesAreNotPresent(Class<?> testClass) {
    for (Field field : testClass.getFields()) {
        Assert.state(!SpringClassRule.class.isAssignableFrom(field.getType()),
                () -> String.format(
                        "Detected SpringClassRule field in test class [%s], "
                                + "but SpringClassRule cannot be used with the SpringJUnit4ClassRunner.",
                        testClass.getName()));
        Assert.state(!SpringMethodRule.class.isAssignableFrom(field.getType()),
                () -> String.format(
                        "Detected SpringMethodRule field in test class [%s], "
                                + "but SpringMethodRule cannot be used with the SpringJUnit4ClassRunner.",
                        testClass.getName()));
    }/*from w w  w .  j a  v  a  2  s .  c  om*/
}

From source file:org.pentaho.reporting.engine.classic.core.style.StyleKey.java

public static synchronized void registerClass(final Class c) {
    // Log.debug ("Registering stylekeys from " + c);
    try {//from ww  w. ja v  a  2 s  .  co m
        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());
    }
}

From source file:org.assertj.assertions.generator.util.ClassUtil.java

public static List<Field> nonStaticPublicFieldsOf(Class<?> clazz) {
    Field[] fields = clazz.getFields();
    List<Field> nonStaticPublicFields = new ArrayList<Field>();
    for (Field field : fields) {
        if (isNotStaticPublicField(field)) {
            nonStaticPublicFields.add(field);
        }/* w ww  .  ja  va2  s . c  o  m*/
    }
    return nonStaticPublicFields;
}

From source file:org.springframework.richclient.util.ClassUtils.java

/**
 * Returns the qualified class field name with the specified value. For
 * example, with a class defined with a static field "NORMAL" with value =
 * "0", passing in "0" would return: className.NORMAL.
 *
 * @return The qualified field.//from  w w w.java 2s.  c o m
 */
public static String getClassFieldNameWithValue(Class clazz, Object value) {
    Field[] fields = clazz.getFields();
    for (int i = 0; i < fields.length; i++) {
        Field field = fields[i];
        try {
            Object constant = field.get(null);
            if (value.equals(constant)) {
                return clazz.getName() + "." + field.getName();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    return null;
}

From source file:io.github.wysohn.triggerreactor.tools.ReflectionUtil.java

public static List<Field> getAllPublicFields(List<Field> fields, Class<?> c) {
    fields.addAll(Arrays.asList(c.getFields()));

    if (c.getSuperclass() != null) {
        fields = getAllPublicFields(fields, c.getSuperclass());
    }//from   w w w  . j av  a 2s.c  om

    return fields;
}

From source file:com.jilk.ros.rosbridge.implementation.JSON.java

private static Message convertJSONObjectToMessage(JSONObject jo, Class c, Registry<Class> r) {
    //System.out.println("JSON.convertJSONObjectToMessage: " + jo.toJSONString());
    try {//from www .  j a  va  2 s  .  c om
        Message result = (Message) c.newInstance();
        for (Field f : c.getFields()) {
            Class fc = getFieldClass(result, jo, f, r);
            Object lookup = jo.get(f.getName());
            if (lookup != null) {
                Object value = convertElementToField(lookup, fc, f, r);
                f.set(result, value);
            }
        }
        return result;
    } catch (Exception ex) {
        //ex.printStackTrace();
        return null;
    }
}

From source file:org.gradle.internal.reflect.JavaReflectionUtil.java

private static Field findField(Class<?> target, String fieldName) {
    Field[] fields = target.getFields();
    for (Field field : fields) {
        if (fieldName.equals(field.getName())) {
            return field;
        }/* w w w. j  a v a2  s  .com*/
    }
    return null;
}