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:org.apache.hadoop.hbase.hbql.impl.Utils.java

public static void checkForDefaultConstructors(final Class clazz) {

    if (!clazz.getName().contains("hadoop"))
        return;//from   ww w  . j  a  va2  s .c o m

    if (Modifier.isStatic(clazz.getModifiers()))
        return;

    if (classList.contains(clazz))
        return;
    else
        classList.add(clazz);

    if (!hasDefaultConstructor(clazz))
        System.out.println(clazz.getName() + " is missing null constructor");

    Field[] fields = clazz.getDeclaredFields();

    for (final Field field : fields) {
        Class dclazz = field.getType();
        checkForDefaultConstructors(dclazz);
    }

    fields = clazz.getFields();

    for (final Field field : fields) {
        Class dclazz = field.getType();
        checkForDefaultConstructors(dclazz);
    }
}

From source file:com.doitnext.jsonschema.generator.SchemaGen.java

private static boolean handleProperties(Class<?> classz, StringBuilder sb, Map<String, String> declarations,
        String uriPrefix) {/*w  ww. j a  va 2 s .  c  om*/
    boolean result = false;
    String prepend = "";
    Set<String> processedFields = new HashSet<String>();
    sb.append("{");
    for (Field field : classz.getFields()) {
        JsonSchemaProperty propertyDecl = field.getAnnotation(JsonSchemaProperty.class);
        if (propertyDecl != null) {
            Class<?> propClassz = field.getType();
            StringBuilder sb2 = new StringBuilder();
            boolean inline = true;
            sb2.append("{");
            if (!handleSimpleType(propClassz, sb2, propertyDecl, declarations, uriPrefix)) {
                if (!handleArrayType(propClassz, sb2, propertyDecl, declarations, uriPrefix)) {
                    inline = false;
                }
            }
            sb2.append("}");
            if (inline) {
                sb.append(prepend);
                sb.append("\"");
                sb.append(propertyDecl.name());
                sb.append("\":");
                sb.append(sb2.toString());
                prepend = ", ";
            } else {
                String id = null;
                JsonSchemaClass jsc = propClassz.getAnnotation(JsonSchemaClass.class);
                if (jsc != null)
                    id = jsc.id();
                else
                    id = propClassz.getName();
                declarations.put(id, sb2.toString());

                sb.append(prepend);
                sb.append("\"");
                sb.append(propertyDecl.name());
                sb.append("\":{\"$ref\":\"");
                if (!StringUtils.isEmpty(uriPrefix))
                    sb.append(uriPrefix);
                sb.append(id);
                sb.append("\"}");
                prepend = ", ";
            }
            processedFields.add(propertyDecl.name());
        }
    }
    for (Method method : classz.getMethods()) {
        JsonSchemaProperty propertyDecl = method.getAnnotation(JsonSchemaProperty.class);
        if (propertyDecl != null && !processedFields.contains(propertyDecl.name())) {
            Class<?> propClassz = method.getReturnType();
            StringBuilder sb2 = new StringBuilder();
            boolean inline = true;
            sb2.append("{");
            if (!handleSimpleType(propClassz, sb2, propertyDecl, declarations, uriPrefix)) {
                if (!handleArrayType(propClassz, sb2, propertyDecl, declarations, uriPrefix)) {
                    inline = false;
                }
            }
            sb2.append("}");
            if (inline) {
                sb.append(prepend);
                sb.append("\"");
                sb.append(propertyDecl.name());
                sb.append("\":");
                sb.append(sb2.toString());
                prepend = ", ";
            } else {
                String id = null;
                JsonSchemaClass jsc = propClassz.getAnnotation(JsonSchemaClass.class);
                if (jsc != null)
                    id = jsc.id();
                else
                    id = propClassz.getName();
                declarations.put(id, sb2.toString());

                sb.append(prepend);
                sb.append("\"");
                sb.append(propertyDecl.name());
                sb.append("\":{\"$ref\":\"");
                if (!StringUtils.isEmpty(uriPrefix))
                    sb.append(uriPrefix);
                sb.append(id);
                sb.append("\"}");
                prepend = ", ";
            }
            processedFields.add(propertyDecl.name());
        }
    }
    sb.append("}");
    return result;
}

From source file:com.eviware.x.form.support.ADialogBuilder.java

public static XFormDialog buildWizard(Class<? extends Object> tabbedFormClass) {
    AForm formAnnotation = tabbedFormClass.getAnnotation(AForm.class);
    if (formAnnotation == null) {
        throw new RuntimeException("formClass is not annotated correctly..");
    }//from ww  w.j a  v a 2 s  .  co m

    MessageSupport messages = MessageSupport.getMessages(tabbedFormClass);
    XFormDialogBuilder builder = XFormFactory.createDialogBuilder(formAnnotation.name());

    for (Field field : tabbedFormClass.getFields()) {
        APage pageAnnotation = field.getAnnotation(APage.class);
        if (pageAnnotation != null) {
            buildForm(builder, pageAnnotation.name(), field.getType(), messages);
        }
    }

    XFormDialog dialog = builder.buildWizard(formAnnotation.description(),
            UISupport.createImageIcon(formAnnotation.icon()), formAnnotation.helpUrl());

    return dialog;
}

From source file:com.scvngr.levelup.core.test.JsonTestUtil.java

/**
 * <p>//  w  ww .j a  va 2s  .  co m
 * Checks that modifying individual fields in a model will result in its equals/hashCode methods
 * failing. Uses reflection on {@link JsonValueType} annotations on fields of a passed class to
 * figure out how to modify the JSON representation of the model in different ways, then parses
 * the JSON with a {@link AbstractJsonModelFactory} subclass before checking equals/hashcode on
 * both the original and a modified object.
 * </p>
 * <p>
 * This effectively checks that equals/hashcode works across any value changes from fields we
 * read from JSON, but also checks some other potential issues. We're implicitly checking that
 * the JSON typing declared in annotations for the fields matches what we actually use when
 * parsing our JSON (since if it doesn't, we'll get JSON errors when reading the data during the
 * clone/modify). We're also checking for fields that may have been added to the JSON keys and
 * the model without updating equals/hashcode to reflect them (as long as they're declared in
 * the JSONKeys class used here).
 * </p>
 * <p>
 * Note that this is only intended for test use and will turn all checked exceptions it might
 * throw into unchecked ones.
 * </p>
 *
 * @param jsonKeysClass Class of the underlying keys class to test all fields (except
 *        blacklistFields) from. Must have visible fields to read from.
 * @param jsonFactory Factory object to construct model instances from out of the base and
 *        generated-variant JSON objects before checking equals/hashcode.
 * @param baseJsonObject Fully-populated JSON object for the model to use for comparison with
 *        modified copies.
 * @param blacklistFields Fields to exclude from variant testing (either because we need to test
 *        them manually or because they don't reflect fields that are used for parsing into the
 *        model). Note that this is the jsonKeysClass's field name as a string, not the JSON key
 *        value (eg "ID", not "id").
 */
public static void checkEqualsAndHashCodeOnJsonVariants(@NonNull final Class<?> jsonKeysClass,
        @NonNull final AbstractJsonModelFactory<?> jsonFactory, @NonNull final JSONObject baseJsonObject,
        @NonNull final String[] blacklistFields) {
    Object originalModel;
    Object differentModel;
    Object differentModelReparse;

    try {
        originalModel = jsonFactory.from(baseJsonObject);
    } catch (final JSONException e1) {
        throw new RuntimeException(e1);
    }

    MoreAsserts.checkEqualsAndHashCodeMethods(originalModel, null, false);

    final Field[] jsonKeyFields = jsonKeysClass.getFields();
    final List<String> blacklisted = Arrays.asList(blacklistFields);
    final String key = null;

    MoreAsserts.assertNotEmpty("JSON keys class visible fields", Arrays.asList(jsonKeyFields));

    for (final Field field : jsonKeyFields) {
        if (!blacklisted.contains(field.getName())) {
            JSONObject copiedDifferingObject;
            String fieldString;
            // Don't check exceptions, just let tests fail.
            try {
                fieldString = NullUtils.nonNullContract((String) field.get(key));
                copiedDifferingObject = cloneObjectDifferingOnParam(baseJsonObject, fieldString,
                        reflectJsonType(field));
                differentModel = jsonFactory.from(copiedDifferingObject);
                differentModelReparse = jsonFactory.from(copiedDifferingObject);
            } catch (final IllegalArgumentException e) {
                throw new RuntimeException(e);
            } catch (final IllegalAccessException e) {
                throw new RuntimeException(e);
            } catch (final JSONException e) {
                throw new RuntimeException(e);
            }

            MoreAsserts.checkEqualsAndHashCodeMethods(
                    String.format(Locale.US, "Modified %s and checked equals and hash", fieldString),
                    originalModel, differentModel, false);
            MoreAsserts.checkEqualsAndHashCodeMethods(
                    String.format(Locale.US, "Modified %s and checked equals and hash", fieldString),
                    differentModel, differentModel, true);
            MoreAsserts.checkEqualsAndHashCodeMethods(
                    String.format(Locale.US, "Modified %s and checked equals and hash", fieldString),
                    differentModel, differentModelReparse, true);
        }
    }
}

From source file:com.eviware.x.form.support.ADialogBuilder.java

public static XFormDialog buildTabbedDialog(Class<? extends Object> tabbedFormClass, ActionList actions) {
    AForm formAnnotation = tabbedFormClass.getAnnotation(AForm.class);
    if (formAnnotation == null) {
        throw new RuntimeException("formClass is not annotated correctly..");
    }/*from   ww w  . ja  va2  s  . c o m*/

    MessageSupport messages = MessageSupport.getMessages(tabbedFormClass);
    XFormDialogBuilder builder = XFormFactory.createDialogBuilder(formAnnotation.name());

    for (Field field : tabbedFormClass.getFields()) {
        APage pageAnnotation = field.getAnnotation(APage.class);
        if (pageAnnotation != null) {
            buildForm(builder, pageAnnotation.name(), field.getType(), messages);
        }

        AField fieldAnnotation = field.getAnnotation(AField.class);
        if (fieldAnnotation != null) {
            try {
                Class<?> formClass = Class.forName(fieldAnnotation.description());
                buildForm(builder, fieldAnnotation.name(), formClass, messages);
            } catch (Exception e) {
                SoapUI.logError(e);
            }
        }
    }

    ActionList defaultActions = StringUtils.isBlank(formAnnotation.helpUrl()) ? builder.buildOkCancelActions()
            : builder.buildOkCancelHelpActions(formAnnotation.helpUrl());

    if (actions == null) {
        actions = defaultActions;
    } else {
        actions.addActions(defaultActions);
    }

    XFormDialog dialog = builder.buildDialog(actions, formAnnotation.description(),
            UISupport.createImageIcon(formAnnotation.icon()));

    return dialog;
}

From source file:org.eclipse.skalli.model.EntityBase.java

private static Map<String, Method> getReadAccessors(Class<? extends EntityBase> entityClass) {
    Map<String, Method> accessors = new HashMap<String, Method>();
    if (entityClass != null) {
        for (Field field : entityClass.getFields()) {
            if (field.getAnnotation(PropertyName.class) != null) {
                try {
                    String propertyName = (String) field.get(null);
                    if (StringUtils.isBlank(propertyName)) {
                        throw new IllegalArgumentException(
                                MessageFormat.format("@PropertyName {0} defines a blank property name", field));
                    }/* www .j  a  va  2  s.  c  o  m*/
                    Method accessor = getReadAccessor(entityClass, propertyName, null);
                    if (accessor != null) {
                        accessors.put(propertyName, accessor);
                    }
                } catch (Exception e) {
                    throw new IllegalArgumentException(
                            MessageFormat.format("Invalid @PropertyName declaration: {0}", field), e);
                }
            }
        }
    }
    return Collections.unmodifiableMap(accessors);
}

From source file:com.eviware.x.form.support.ADialogBuilder.java

public static XFormDialog buildTabbedDialogWithCustomActions(Class<? extends Object> tabbedFormClass,
        ActionList actions) {/* w  w w  .  j  a v a  2s.c  o  m*/
    AForm formAnnotation = tabbedFormClass.getAnnotation(AForm.class);
    if (formAnnotation == null) {
        throw new RuntimeException("formClass is not annotated correctly..");
    }

    MessageSupport messages = MessageSupport.getMessages(tabbedFormClass);
    XFormDialogBuilder builder = XFormFactory.createDialogBuilder(formAnnotation.name());

    for (Field field : tabbedFormClass.getFields()) {
        APage pageAnnotation = field.getAnnotation(APage.class);
        if (pageAnnotation != null) {
            buildForm(builder, pageAnnotation.name(), field.getType(), messages);
        }

        AField fieldAnnotation = field.getAnnotation(AField.class);
        if (fieldAnnotation != null) {
            try {
                Class<?> formClass = Class.forName(fieldAnnotation.description());
                buildForm(builder, fieldAnnotation.name(), formClass, messages);
            } catch (Exception e) {
                SoapUI.logError(e);
            }
        }
    }

    ActionList defaultActions = StringUtils.isBlank(formAnnotation.helpUrl()) ? null
            : builder.buildHelpActions(formAnnotation.helpUrl());

    if (actions == null) {
        actions = defaultActions;
    } else {
        defaultActions.addActions(actions);
        actions = defaultActions;
    }

    XFormDialog dialog = builder.buildDialog(actions, formAnnotation.description(),
            UISupport.createImageIcon(formAnnotation.icon()));

    return dialog;
}

From source file:ar.com.zauber.commons.repository.BaseEntity.java

/**
 * @param theClass/*from   w  ww  .j av  a 2  s.c  o m*/
 * @return
 */
private static Set<Field> getIdentityFields(final Class<?> theClass) {
    Set<Field> fields = new HashSet<Field>();
    if (theClass.getAnnotation(IdentityProperties.class) != null) {
        String[] fieldNamesArray = theClass.getClass().getAnnotation(IdentityProperties.class).fieldNames();
        for (int i = 0; i < fieldNamesArray.length; i++) {
            try {
                fields.add((theClass.getField(fieldNamesArray[i])));
            } catch (final SecurityException e) {
                throw new IllegalStateException(e);
            } catch (final NoSuchFieldException e) {
                throw new IllegalStateException(e);
            }

        }
    } else {
        Field[] fieldsArray = theClass.getFields();
        for (int i = 0; i < fieldsArray.length; i++) {
            if (fieldsArray[i].getAnnotation(IdentityProperty.class) != null) {
                fields.add(fieldsArray[i]);
            }
        }
        if (!theClass.getSuperclass().equals(Object.class)) {
            fields.addAll(getIdentityFields(theClass.getSuperclass()));
        }
    }
    return fields;
}

From source file:org.apache.axis.utils.BeanUtils.java

public static BeanPropertyDescriptor[] processPropertyDescriptors(PropertyDescriptor[] rawPd, Class cls,
        TypeDesc typeDesc) {/*from  w  ww.  ja v  a2s .  com*/

    // Create a copy of the rawPd called myPd
    BeanPropertyDescriptor[] myPd = new BeanPropertyDescriptor[rawPd.length];

    ArrayList pd = new ArrayList();

    try {
        for (int i = 0; i < rawPd.length; i++) {
            // Skip the special "any" field
            if (rawPd[i].getName().equals(Constants.ANYCONTENT))
                continue;
            pd.add(new BeanPropertyDescriptor(rawPd[i]));
        }

        // Now look for public fields
        Field fields[] = cls.getFields();
        if (fields != null && fields.length > 0) {
            // See if the field is in the list of properties
            // add it if not.
            for (int i = 0; i < fields.length; i++) {
                Field f = fields[i];
                // skip if field come from a java.* or javax.* package
                // WARNING: Is this going to make bad things happen for
                // users JavaBeans?  Do they WANT these fields serialzed?
                String clsName = f.getDeclaringClass().getName();
                if (clsName.startsWith("java.") || clsName.startsWith("javax.")) {
                    continue;
                }
                // skip field if it is final, transient, or static
                if (!(Modifier.isStatic(f.getModifiers()) || Modifier.isFinal(f.getModifiers())
                        || Modifier.isTransient(f.getModifiers()))) {
                    String fName = f.getName();
                    boolean found = false;
                    for (int j = 0; j < rawPd.length && !found; j++) {
                        String pName = ((BeanPropertyDescriptor) pd.get(j)).getName();
                        if (pName.length() == fName.length()
                                && pName.substring(0, 1).equalsIgnoreCase(fName.substring(0, 1))) {

                            found = pName.length() == 1 || pName.substring(1).equals(fName.substring(1));
                        }
                    }

                    if (!found) {
                        pd.add(new FieldPropertyDescriptor(f.getName(), f));
                    }
                }
            }
        }

        // If typeDesc meta data exists, re-order according to the fields
        if (typeDesc != null && typeDesc.getFields(true) != null) {
            ArrayList ordered = new ArrayList();
            // Add the TypeDesc elements first
            FieldDesc[] fds = typeDesc.getFields(true);
            for (int i = 0; i < fds.length; i++) {
                FieldDesc field = fds[i];
                if (field.isElement()) {
                    boolean found = false;
                    for (int j = 0; j < pd.size() && !found; j++) {
                        if (field.getFieldName().equals(((BeanPropertyDescriptor) pd.get(j)).getName())) {
                            ordered.add(pd.remove(j));
                            found = true;
                        }
                    }
                }
            }
            // Add the remaining elements
            while (pd.size() > 0) {
                ordered.add(pd.remove(0));
            }
            // Use the ordered list
            pd = ordered;
        }

        myPd = new BeanPropertyDescriptor[pd.size()];
        for (int i = 0; i < pd.size(); i++) {
            myPd[i] = (BeanPropertyDescriptor) pd.get(i);
        }
    } catch (Exception e) {
        log.error(Messages.getMessage("badPropertyDesc00", cls.getName()), e);
        throw new InternalException(e);
    }

    return myPd;
}

From source file:com.taobao.weex.wson.Wson.java

private static final List<Field> getBeanFields(String key, Class targetClass) {
    List<Field> fieldList = fieldsCache.get(key);
    if (fieldList == null) {
        Field[] fields = targetClass.getFields();
        fieldList = new ArrayList<>(fields.length);
        for (Field field : fields) {
            if ((field.getModifiers() & Modifier.STATIC) != 0) {
                continue;
            }/*  w  ww .  j a  va  2  s  .c  om*/
            if (field.getAnnotation(JSONField.class) != null) {
                throw new UnsupportedOperationException(
                        "getBeanMethod JSONField Annotation Not Handled, Use toJSON");
            }
            fieldList.add(field);
        }
        fieldsCache.put(key, fieldList);
    }
    return fieldList;
}