Example usage for java.lang.reflect Field getType

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

Introduction

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

Prototype

public Class<?> getType() 

Source Link

Document

Returns a Class object that identifies the declared type for the field represented by this Field object.

Usage

From source file:io.github.benas.randombeans.util.ReflectionUtils.java

/**
 * Check if a field has a primitive type and matching default value which is set by the compiler.
 *
 * @param object instance to get the field value of
 * @param field  field to check/*ww w .  j  a  va 2  s.  c om*/
 * @throws IllegalAccessException if field cannot be accessed
 */
public static boolean isPrimitiveFieldWithDefaultValue(final Object object, final Field field)
        throws IllegalAccessException {
    Class<?> fieldType = field.getType();
    if (!fieldType.isPrimitive()) {
        return false;
    }
    Object fieldValue = getFieldValue(object, field);
    if (fieldValue == null) {
        return false;
    }
    if (fieldType.equals(boolean.class) && (boolean) fieldValue == false) {
        return true;
    }
    if (fieldType.equals(byte.class) && (byte) fieldValue == (byte) 0) {
        return true;
    }
    if (fieldType.equals(short.class) && (short) fieldValue == (short) 0) {
        return true;
    }
    if (fieldType.equals(int.class) && (int) fieldValue == 0) {
        return true;
    }
    if (fieldType.equals(long.class) && (long) fieldValue == 0L) {
        return true;
    }
    if (fieldType.equals(float.class) && (float) fieldValue == 0.0F) {
        return true;
    }
    if (fieldType.equals(double.class) && (double) fieldValue == 0.0D) {
        return true;
    }
    if (fieldType.equals(char.class) && (char) fieldValue == '\u0000') {
        return true;
    }
    return false;
}

From source file:org.nuxeo.apidoc.introspection.ServerInfo.java

protected static List<Class<?>> getSPI(Class<?> klass) {
    List<Class<?>> spi = new ArrayList<>();
    for (Field field : klass.getDeclaredFields()) {
        String cName = field.getType().getCanonicalName();
        if (cName.startsWith("org.nuxeo")) {
            // remove XObjects
            Class<?> fieldClass = field.getType();
            Annotation[] annotations = fieldClass.getDeclaredAnnotations();
            if (annotations.length == 0) {
                spi.add(fieldClass);/*  w w  w .  ja v a2s  . com*/
            }
        }
    }
    return spi;
}

From source file:org.cybercat.automation.annotations.AnnotationBuilder.java

@SuppressWarnings("unchecked")
private static final void createIntegrationService(Field field, Object targetObject)
        throws AutomationFrameworkException {
    Class<IIntegrationService> clazz;
    try {/*from  www . jav  a2s .c  om*/
        clazz = (Class<IIntegrationService>) field.getType();
    } catch (Exception e) {
        throw new AutomationFrameworkException("Unexpected field type :" + field.getType().getSimpleName()
                + " field name: " + field.getName() + " class: " + targetObject.getClass().getSimpleName()
                + " Thread ID:" + Thread.currentThread().getId()
                + " \n\tThis field must be of the type that extends AbstractPageObject class.", e);
    }
    try {

        field.set(targetObject,
                createIntegrationService(clazz, field.getAnnotation(CCIntegrationService.class)));
    } catch (Exception e) {
        throw new AutomationFrameworkException(
                "Set filed exception. Please, save this log and contact the Cybercat project support."
                        + " field name: " + field.getName() + " class: "
                        + targetObject.getClass().getSimpleName() + " Thread ID:"
                        + Thread.currentThread().getId(),
                e);
    }

}

From source file:at.alladin.rmbt.shared.hstoreparser.HstoreParser.java

/**
 * //ww w. j  a va 2 s  . c  om
 * @param json
 * @param key
 * @param toField
 * @return
 * @throws JSONException
 */
public static Object getFromJsonByField2(JSONObject json, String key, Field toField) throws JSONException {
    final Object o = json.get(key);
    final Class<?> fieldType = toField.getType();
    if (o != JSONObject.NULL) {
        if (fieldType.equals(Integer.class) || fieldType.equals(Integer.TYPE)) {
            return json.getInt(key);
        } else if (fieldType.equals(String.class)) {
            return o;
        } else if (fieldType.equals(Long.class) || fieldType.equals(Long.TYPE)) {
            return json.getLong(key);
        } else if (fieldType.equals(Boolean.class) || fieldType.equals(Boolean.TYPE)) {
            return json.getBoolean(key);
        } else if (fieldType.equals(Float.class) || fieldType.equals(Float.TYPE)) {
            return (float) json.getDouble(key);
        } else if (fieldType.equals(Double.class) || fieldType.equals(Double.TYPE)) {
            return json.getDouble(key);
        } else {
            return o;
        }
    }

    return JSONObject.NULL;
}

From source file:edu.mit.csail.sdg.alloy4.Terminal.java

private static String getAvaliableSatSolvers() {
    StringBuilder sb = new StringBuilder();
    for (Field f : A4Options.SatSolver.class.getFields()) {
        if (A4Options.SatSolver.class.isAssignableFrom(f.getType())) {
            sb.append(f.getName() + ", ");
        }/*ww  w .j av  a2 s  .c om*/
    }
    if (sb.length() > 2) {
        sb.delete(sb.length() - 2, sb.length());
    }
    return sb.toString();
}

From source file:io.apiman.manager.api.es.EsMarshallingTest.java

/**
 * Fabricates a new instance of the given bean type.  Uses reflection to figure
 * out all the fields and assign generated values for each.
 *//*from   w  w  w. j a v  a 2  s . co m*/
private static <T> T createBean(Class<T> beanClass) throws InstantiationException, IllegalAccessException,
        InvocationTargetException, NoSuchMethodException, SecurityException, ClassNotFoundException {
    T bean = beanClass.newInstance();
    Map<String, String> beanProps = BeanUtils.describe(bean);
    for (String key : beanProps.keySet()) {
        try {
            Field declaredField = beanClass.getDeclaredField(key);
            Class<?> fieldType = declaredField.getType();
            if (fieldType == String.class) {
                BeanUtils.setProperty(bean, key, StringUtils.upperCase(key));
            } else if (fieldType == Boolean.class || fieldType == boolean.class) {
                BeanUtils.setProperty(bean, key, Boolean.TRUE);
            } else if (fieldType == Date.class) {
                BeanUtils.setProperty(bean, key, new Date(1));
            } else if (fieldType == Long.class || fieldType == long.class) {
                BeanUtils.setProperty(bean, key, 17L);
            } else if (fieldType == Integer.class || fieldType == long.class) {
                BeanUtils.setProperty(bean, key, 11);
            } else if (fieldType == Set.class) {
                // Initialize to a linked hash set so that order is maintained.
                BeanUtils.setProperty(bean, key, new LinkedHashSet());

                Type genericType = declaredField.getGenericType();
                String typeName = genericType.getTypeName();
                String typeClassName = typeName.substring(14, typeName.length() - 1);
                Class<?> typeClass = Class.forName(typeClassName);
                Set collection = (Set) BeanUtilsBean.getInstance().getPropertyUtils().getProperty(bean, key);
                populateSet(collection, typeClass);
            } else if (fieldType == Map.class) {
                Map<String, String> map = new LinkedHashMap<String, String>();
                map.put("KEY-1", "VALUE-1");
                map.put("KEY-2", "VALUE-2");
                BeanUtils.setProperty(bean, key, map);
            } else if (fieldType.isEnum()) {
                BeanUtils.setProperty(bean, key, fieldType.getEnumConstants()[0]);
            } else if (fieldType.getPackage() != null
                    && fieldType.getPackage().getName().startsWith("io.apiman.manager.api.beans")) {
                Object childBean = createBean(fieldType);
                BeanUtils.setProperty(bean, key, childBean);
            } else {
                throw new IllegalAccessException(
                        "Failed to handle property named [" + key + "] type: " + fieldType.getSimpleName());
            }
            //            String capKey = StringUtils.capitalize(key);
            //            System.out.println(key);;
        } catch (NoSuchFieldException e) {
            // Skip it - there is not really a bean property with this name!
        }
    }
    return bean;
}

From source file:com.ery.ertc.estorm.util.ClassSize.java

/**
 * The estimate of the size of a class instance depends on whether the JVM uses 32 or 64 bit addresses, that is it depends on the size
 * of an object reference. It is a linear function of the size of a reference, e.g. 24 + 5*r where r is the size of a reference (usually
 * 4 or 8 bytes).// w  w w .  j  a  v  a 2  s  . com
 * 
 * This method returns the coefficients of the linear function, e.g. {24, 5} in the above example.
 * 
 * @param cl
 *            A class whose instance size is to be estimated
 * @param debug
 *            debug flag
 * @return an array of 3 integers. The first integer is the size of the primitives, the second the number of arrays and the third the
 *         number of references.
 */
@SuppressWarnings("unchecked")
private static int[] getSizeCoefficients(Class cl, boolean debug) {
    int primitives = 0;
    int arrays = 0;
    // The number of references that a new object takes
    int references = nrOfRefsPerObj;
    int index = 0;

    for (; null != cl; cl = cl.getSuperclass()) {
        Field[] field = cl.getDeclaredFields();
        if (null != field) {
            for (Field aField : field) {
                if (Modifier.isStatic(aField.getModifiers()))
                    continue;
                Class fieldClass = aField.getType();
                if (fieldClass.isArray()) {
                    arrays++;
                    references++;
                } else if (!fieldClass.isPrimitive()) {
                    references++;
                } else {// Is simple primitive
                    String name = fieldClass.getName();

                    if (name.equals("int") || name.equals("I"))
                        primitives += Bytes.SIZEOF_INT;
                    else if (name.equals("long") || name.equals("J"))
                        primitives += Bytes.SIZEOF_LONG;
                    else if (name.equals("boolean") || name.equals("Z"))
                        primitives += Bytes.SIZEOF_BOOLEAN;
                    else if (name.equals("short") || name.equals("S"))
                        primitives += Bytes.SIZEOF_SHORT;
                    else if (name.equals("byte") || name.equals("B"))
                        primitives += Bytes.SIZEOF_BYTE;
                    else if (name.equals("char") || name.equals("C"))
                        primitives += Bytes.SIZEOF_CHAR;
                    else if (name.equals("float") || name.equals("F"))
                        primitives += Bytes.SIZEOF_FLOAT;
                    else if (name.equals("double") || name.equals("D"))
                        primitives += Bytes.SIZEOF_DOUBLE;
                }
                if (debug) {
                    if (LOG.isDebugEnabled()) {
                        LOG.debug("" + index + " " + aField.getName() + " " + aField.getType());
                    }
                }
                index++;
            }
        }
    }
    return new int[] { primitives, arrays, references };
}

From source file:de.micromata.genome.util.runtime.ClassUtils.java

/**
 * Set all String field to empty on current class.
 *
 * @param object the object//from ww  w .ja va  2  s.  com
 * @param exceptClass the except class
 * @throws IllegalArgumentException the illegal argument exception
 * @throws IllegalAccessException the illegal access exception
 */
// CHECKSTYLE.OFF com.puppycrawl.tools.checkstyle.checks.metrics.CyclomaticComplexityCheck Trivial code.
public static void fillDefaultEmptyFieldsIfEmpty(Object object, Class<?>... exceptClass) // NOSONAR "Methods should not be too complex" trivial
        throws IllegalArgumentException, IllegalAccessException {
    Class<?> currentClazz = object.getClass();
    List exClazzes = Arrays.asList(exceptClass);
    while (currentClazz.getSuperclass() != null) {
        if (exClazzes.contains(currentClazz) == false) {
            Field[] fields = currentClazz.getDeclaredFields();
            for (Field field : fields) {
                if (String.class.equals(field.getType())) {
                    field.setAccessible(true);
                    if (field.get(object) == null) {
                        field.set(object, "");
                    }
                }
                if (Integer.class.equals(field.getType())) {
                    field.setAccessible(true);
                    if (field.get(object) == null) {
                        field.set(object, 0);
                    }
                }
                if (BigDecimal.class.equals(field.getType())) {
                    field.setAccessible(true);
                    if (field.get(object) == null) {
                        field.set(object, BigDecimal.ZERO);
                    }
                }
                if (Date.class.equals(field.getType())) {
                    field.setAccessible(true);
                    if (field.get(object) == null) {
                        field.set(object, new Date());
                    }
                }
            }
        }
        currentClazz = currentClazz.getSuperclass();
    }
}

From source file:com.lonepulse.zombielink.proxy.Zombie.java

/**
 * <p>Accepts an object and scans it for {@link Bite} annotations. If found, a <b>thread-safe proxy</b> 
 * for the endpoint interface will be injected.</p>
 * //w  w w .  j  av  a 2s .  c  o m
 * <p>Injection targets will be searched up an inheritance hierarchy until a type is found which is 
 * <b>not</b> in a package whose name starts with the given package prefixes.</p>
 * <br>
 * <b>Usage:</b>
 * <br><br>
 * <ul>
 * <li>
 * <h5>Property Injection</h5>
 * <pre>
 * <code><b>@Bite</b>
 * private GitHubEndpoint gitHubEndpoint;
 * {
 * &nbsp; &nbsp; Zombie.infect(Arrays.asList("com.example.service", "com.example.manager"), this);
 * }
 * </code>
 * </pre>
 * </li>
 * <li>
 * <h5>Setter Injection</h5>
 * <pre>
 * <code><b>@Bite</b>
 * private GitHubEndpoint gitHubEndpoint;
 * {
 * &nbsp; &nbsp; Zombie.infect(Arrays.asList("com.example.service", "com.example.manager"), this);
 * }
 * </code>
 * <code>
 * public void setGitHubEndpoint(GitHubEndpoint gitHubEndpoint) {
 * 
 * &nbsp; &nbsp; this.gitHubEndpoint = gitHubEndpoint;
 * }
 * </code>
 * </pre>
 * </li>
 * </ul>
 * 
 * @param packagePrefixes
 *          the prefixes of packages to restrict hierarchical lookup of injection targets; if {@code null} 
 *          or {@code empty}, {@link #infect(Object, Object...)} will be used
 * <br><br>
 * @param victim
 *          an object with endpoint references marked to be <i>bitten</i> and infected 
 * <br><br>
 * @param moreVictims
 *          more unsuspecting objects with endpoint references to be infected
 * <br><br>
 * @throws NullPointerException
 *          if the object supplied for endpoint injection is {@code null} 
 * <br><br>
 * @since 1.3.0
 */
public static void infect(List<String> packagePrefixes, Object victim, Object... moreVictims) {

    assertNotNull(victim);

    List<Object> injectees = new ArrayList<Object>();
    injectees.add(victim);

    if (moreVictims != null && moreVictims.length > 0) {

        injectees.addAll(Arrays.asList(moreVictims));
    }

    Class<?> endpointInterface = null;

    for (Object injectee : injectees) {

        Class<?> type = injectee.getClass();

        do {

            for (Field field : Fields.in(type).annotatedWith(Bite.class)) {

                try {

                    endpointInterface = field.getType();
                    Object proxyInstance = EndpointProxyFactory.INSTANCE.create(endpointInterface);

                    try { //1.Simple Field Injection 

                        field.set(injectee, proxyInstance);
                    } catch (IllegalAccessException iae) { //2.Setter Injection 

                        String fieldName = field.getName();
                        String mutatorName = "set" + Character.toUpperCase(fieldName.charAt(0))
                                + fieldName.substring(1);

                        try {

                            Method mutator = injectee.getClass().getDeclaredMethod(mutatorName,
                                    endpointInterface);
                            mutator.invoke(injectee, proxyInstance);
                        } catch (NoSuchMethodException nsme) { //3.Forced Field Injection

                            field.setAccessible(true);
                            field.set(injectee, proxyInstance);
                        }
                    }
                } catch (Exception e) {

                    Logger.getLogger(Zombie.class.getName()).log(Level.SEVERE,
                            new StringBuilder().append("Failed to inject the endpoint proxy instance of type ")
                                    .append(endpointInterface.getName()).append(" on property ")
                                    .append(field.getName()).append(" at ")
                                    .append(injectee.getClass().getName()).append(". ").toString(),
                            e);
                }
            }

            type = type.getSuperclass();
        } while (!hierarchyTerminal(type, packagePrefixes));
    }
}

From source file:at.alladin.rmbt.shared.hstoreparser.HstoreParser.java

/**
 * get a specific key from json by preserving the fields type
 * @param json/*from   w  w  w. jav  a2  s.  co  m*/
 * @param key
 * @param toField
 * @return
 * @throws JSONException 
 */
public static Object getFromJsonByField(JSONObject json, String key, Field toField) throws JSONException {
    final Object o = json.get(key);
    if (o != JSONObject.NULL) {
        if (toField.getType().equals(Integer.class) || toField.getType().equals(Integer.TYPE)) {
            return Integer.parseInt(String.valueOf(o));
        } else if (toField.getType().equals(String.class)) {
            return o;
        } else if (toField.getType().equals(Long.class) || toField.getType().equals(Long.TYPE)) {
            return Long.parseLong(String.valueOf(o));
        } else if (toField.getType().equals(Boolean.class) || toField.getType().equals(Boolean.TYPE)) {
            return Boolean.parseBoolean(String.valueOf(o));
        } else if (toField.getType().equals(Float.class) || toField.getType().equals(Float.TYPE)) {
            return Float.parseFloat(String.valueOf(o));
        } else if (toField.getType().equals(Double.class) || toField.getType().equals(Double.TYPE)) {
            return Double.parseDouble(String.valueOf(o));
        } else {
            return o;
        }
    }

    return JSONObject.NULL;
}