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:io.gravitee.management.service.processor.ApiSynchronizationProcessor.java

public boolean processCheckSynchronization(ApiEntity deployedApi, ApiEntity apiToDeploy) {
    Class<ApiEntity> cl = ApiEntity.class;
    List<Object> requiredFieldsDeployedApi = new ArrayList<Object>();
    List<Object> requiredFieldsApiToDeploy = new ArrayList<Object>();
    for (Field f : cl.getDeclaredFields()) {
        if (f.getAnnotation(DeploymentRequired.class) != null) {
            boolean previousAccessibleState = f.isAccessible();
            f.setAccessible(true);// www.  jav a2 s. c  o m
            try {
                requiredFieldsDeployedApi.add(f.get(deployedApi));
                requiredFieldsApiToDeploy.add(f.get(apiToDeploy));
            } catch (Exception e) {
                LOGGER.error("Error access API required deployment fields", e);
            } finally {
                f.setAccessible(previousAccessibleState);
            }
        }
    }

    try {
        String requiredFieldsDeployedApiDefinition = objectMapper.writeValueAsString(requiredFieldsDeployedApi);
        String requiredFieldsApiToDeployDefinition = objectMapper.writeValueAsString(requiredFieldsApiToDeploy);

        return requiredFieldsDeployedApiDefinition.equals(requiredFieldsApiToDeployDefinition);
    } catch (Exception e) {
        LOGGER.error("Unexpected error while generating API deployment required fields definition", e);
        return false;
    }
}

From source file:alpha.portal.webapp.taglib.ConstantsTei.java

/**
 * Return information about the scripting variables to be created.
 * //from   w w  w.  j a v  a2  s  . c om
 * @param data
 *            the input data
 * @return VariableInfo array of variable information
 */
@Override
public VariableInfo[] getVariableInfo(final TagData data) {
    // loop through and expose all attributes
    final List<VariableInfo> vars = new ArrayList<VariableInfo>();

    try {
        String clazz = data.getAttributeString("className");

        if (clazz == null) {
            clazz = Constants.class.getName();
        }

        final Class c = Class.forName(clazz);

        // if no var specified, get all
        if (data.getAttributeString("var") == null) {
            final Field[] fields = c.getDeclaredFields();

            AccessibleObject.setAccessible(fields, true);

            for (final Field field : fields) {
                final String type = field.getType().getName();
                vars.add(new VariableInfo(field.getName(),
                        ((field.getType().isArray()) ? type.substring(2, type.length() - 1) + "[]" : type),
                        true, VariableInfo.AT_END));
            }
        } else {
            final String var = data.getAttributeString("var");
            final String type = c.getField(var).getType().getName();
            vars.add(new VariableInfo(c.getField(var).getName(),
                    ((c.getField(var).getType().isArray()) ? type.substring(2, type.length() - 1) + "[]"
                            : type),
                    true, VariableInfo.AT_END));
        }
    } catch (final Exception cnf) {
        this.log.error(cnf.getMessage());
        cnf.printStackTrace();
    }

    return vars.toArray(new VariableInfo[] {});
}

From source file:com.madrobot.di.wizard.json.JSONSerializer.java

/**
 * Serialize a specific java object recursively.
 * //w  w  w.  j  a  v  a 2 s. c  om
 * @param jsonObject
 *            Object whose fields need to be set
 * 
 * @param stack
 *            Stack of {@link ClassInfo} - entity type under consideration
 * 
 * @throws JSONException
 *             If an exception occurs during parsing
 */
private void serializer(JSONObject jsonObject, final Stack<Object> stack) throws JSONException {

    Object userObject = stack.peek();
    Class<?> userClass = userObject.getClass();
    Field[] fields = userClass.getDeclaredFields();

    for (Field field : fields) {

        String fieldName = field.getName();
        Class<?> classType = field.getType();
        String jsonKeyName = getKeyName(field);

        try {

            String getMethodName = getGetMethodName(fieldName, classType);
            Method getMethod = userClass.getDeclaredMethod(getMethodName);
            Object returnValue = getMethod.invoke(userObject, new Object[] {});

            if (Converter.isPseudoPrimitive(classType)) {
                Converter.storeValue(jsonObject, jsonKeyName, returnValue, field);
            } else if (Converter.isCollectionType(classType)) {

                JSONArray jsonArray = new JSONArray();
                boolean canAdd = true;

                if (returnValue instanceof Collection) {
                    Collection<?> userCollectionObj = (Collection<?>) returnValue;

                    if (userCollectionObj.size() != 0) {

                        Iterator<?> iterator = userCollectionObj.iterator();

                        while (iterator.hasNext()) {
                            Object itemObject = iterator.next();
                            JSONObject object = new JSONObject();
                            stack.push(itemObject);
                            serializer(object, stack);
                            jsonArray.put(object);
                        }
                    } else if (field.isAnnotationPresent(ItemType.class)) {
                        ItemType itemType = field.getAnnotation(ItemType.class);
                        canAdd = itemType.canEmpty();
                    }

                    if (canAdd)
                        jsonObject.put(jsonKeyName, jsonArray);
                } else if (returnValue instanceof Map) {
                    Map<?, ?> userMapObj = (Map<?, ?>) returnValue;
                    JSONObject object = new JSONObject(userMapObj);
                    jsonArray.put(object);
                    jsonObject.put(jsonKeyName, jsonArray);
                }
            } else {
                stack.push(returnValue);
                JSONObject object = new JSONObject();
                serializer(object, stack);
                jsonObject.put(jsonKeyName, object);
            }

        } catch (NoSuchMethodException e) {
            Log.e(TAG, e.getMessage());
        } catch (IllegalAccessException e) {
            Log.e(TAG, e.getMessage());
        } catch (InvocationTargetException e) {
            Log.e(TAG, e.getMessage());
        }
    }
}

From source file:net.ceos.project.poi.annotated.annotation.XlsElementTest.java

/**
 * Test initialization of the comment attribute with specific value.
 *///from  w ww  .  j a  va  2  s . com
@Test
public void checkCommentAttribute() {
    Class<XMenFactory.Cyclops> oC = XMenFactory.Cyclops.class;

    List<Field> fL = Arrays.asList(oC.getDeclaredFields());
    for (Field f : fL) {
        // Process @XlsElement
        if (f.isAnnotationPresent(XlsElement.class)) {

            XlsElement xlsElement = (XlsElement) f.getAnnotation(XlsElement.class);

            if (StringUtils.isNotBlank(xlsElement.comment())) {
                assertEquals(xlsElement.comment(), "This is a comment");
            }
        }
    }
}

From source file:net.ceos.project.poi.annotated.annotation.XlsElementTest.java

/**
 * Test initialization of the decorator attribute with specific value.
 *//*from  w  w w .  j  a va 2s .  c  om*/
@Test
public void checkDecoratorAttribute() {
    Class<XMenFactory.Cyclops> oC = XMenFactory.Cyclops.class;

    List<Field> fL = Arrays.asList(oC.getDeclaredFields());
    for (Field f : fL) {
        // Process @XlsElement
        if (f.isAnnotationPresent(XlsElement.class)) {

            XlsElement xlsElement = (XlsElement) f.getAnnotation(XlsElement.class);

            if (StringUtils.isNotBlank(xlsElement.decorator())) {
                assertEquals(xlsElement.decorator(), "extendedIntDecorator");
            }
        }
    }
}

From source file:net.ceos.project.poi.annotated.annotation.XlsElementTest.java

/**
 * Test initialization of the formatMask attribute with specific value.
 *//*from  www  . ja va2s  . c  o m*/
@Test
public void checkFormatMaskAttribute() {
    Class<XMenFactory.Cyclops> oC = XMenFactory.Cyclops.class;

    List<Field> fL = Arrays.asList(oC.getDeclaredFields());
    for (Field f : fL) {
        // Process @XlsElement
        if (f.isAnnotationPresent(XlsElement.class)) {

            XlsElement xlsElement = (XlsElement) f.getAnnotation(XlsElement.class);

            if (StringUtils.isNotBlank(xlsElement.formatMask())) {
                assertEquals(xlsElement.formatMask(), "0.000");
            }
        }
    }
}

From source file:net.ceos.project.poi.annotated.annotation.XlsElementTest.java

/**
 * Test initialization of the transformMask attribute with specific value.
 *///  www  . jav  a  2 s .  co m
@Test
public void checkTransformMaskAttribute() {
    Class<XMenFactory.Cyclops> oC = XMenFactory.Cyclops.class;

    List<Field> fL = Arrays.asList(oC.getDeclaredFields());
    for (Field f : fL) {
        // Process @XlsElement
        if (f.isAnnotationPresent(XlsElement.class)) {

            XlsElement xlsElement = (XlsElement) f.getAnnotation(XlsElement.class);

            if (StringUtils.isNotBlank(xlsElement.transformMask())) {
                assertEquals(xlsElement.transformMask(), "0.0");
            }
        }
    }
}

From source file:net.ceos.project.poi.annotated.annotation.XlsElementTest.java

/**
 * Test initialization of the isFormula & formula attribute with specific
 * value./*from   ww w.  j  a v  a 2  s.  co m*/
 */
@Test
public void checkFormulaAttribute() {
    Class<XMenFactory.Cyclops> oC = XMenFactory.Cyclops.class;

    List<Field> fL = Arrays.asList(oC.getDeclaredFields());
    for (Field f : fL) {
        // Process @XlsElement
        if (f.isAnnotationPresent(XlsElement.class)) {

            XlsElement xlsElement = (XlsElement) f.getAnnotation(XlsElement.class);

            if (xlsElement.isFormula()) {
                assertEquals(xlsElement.formula(), "SUM(E3,F3)");
            }
        }
    }
}

From source file:de.codesourcery.eve.skills.util.SpringBeanInjector.java

private void doInjectDependencies(Object obj)
        throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {

    Class<?> currentClasz = obj.getClass();
    do {/*from   ww  w  . j a  v a 2s.  c o  m*/
        // inject fields
        for (Field f : currentClasz.getDeclaredFields()) {

            final int m = f.getModifiers();
            if (Modifier.isStatic(m) || Modifier.isFinal(m)) {
                continue;
            }

            final Resource annot = f.getAnnotation(Resource.class);
            if (annot != null) {
                if (!f.isAccessible()) {
                    f.setAccessible(true);
                }

                if (log.isTraceEnabled()) {
                    log.trace("doInjectDependencies(): Setting field " + f.getName() + " with bean '"
                            + annot.name() + "'");
                }
                f.set(obj, getBean(annot.name()));
            }
        }

        // inject methods
        for (Method method : currentClasz.getDeclaredMethods()) {

            final int m = method.getModifiers();
            if (Modifier.isStatic(m) || Modifier.isAbstract(m)) {
                continue;
            }

            if (method.getParameterTypes().length != 1) {
                continue;
            }

            if (!method.getName().startsWith("set")) {
                continue;
            }

            final Resource annot = method.getAnnotation(Resource.class);
            if (annot != null) {
                if (!method.isAccessible()) {
                    method.setAccessible(true);
                }

                if (log.isTraceEnabled()) {
                    log.trace("doInjectDependencies(): Invoking setter method " + method.getName()
                            + " with bean '" + annot.name() + "'");
                }

                method.invoke(obj, getBean(annot.name()));
            }
        }

        currentClasz = currentClasz.getSuperclass();

    } while (currentClasz != null);
}

From source file:it.unibas.spicy.persistence.object.operators.AnalyzeFields.java

private void extractFields(ClassTree classTree, IClassNode currentNode) {
    Class currentClass = currentNode.getCorrespondingClass();
    Field[] fields = currentClass.getDeclaredFields();
    if (logger.isDebugEnabled())
        logger.debug("number of fields: " + fields.length);
    for (Field field : fields) {
        if (ClassUtility.isTransient(field)) {
            continue;
        }//  w w  w  .j a  v  a 2s  .  co  m
        if (logger.isDebugEnabled())
            logger.debug("Found a non-transient field: " + field);
        if (!isGetAndSetAvailable(field)) {
            throw new IllegalModelException("set and get method not available for field: " + field.getName()
                    + " - Class: " + currentClass);
        }
        if (isPrimitiveType(field) || isWrapperType(field)) {
            generateLeafProperty(currentNode, field);
        } else if (ClassUtility.isAReferenceCollection(field)) {
            generateCollectionOfReferences(classTree, currentNode, field);
        } else {
            generateReferenceProperty(classTree, currentNode, field);
        }
    }
}