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:com.github.jiahut.demo.utils.LoggerPostProcessor.java

@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {

    List<Field> fields = Arrays.asList(bean.getClass().getDeclaredFields());

    for (Field field : fields) {
        if (Logger.class.isAssignableFrom(field.getType()) && field.getAnnotation(InjectLogger.class) != null) {

            logger.debug("Attempting to inject a SLF4J logger on bean: " + bean.getClass());

            if (field != null && (field.getModifiers() & Modifier.STATIC) == 0) {
                field.setAccessible(true);
                try {
                    field.set(bean, LoggerFactory.getLogger(bean.getClass()));
                    logger.debug("Successfully injected a SLF4J logger on bean: " + bean.getClass());
                } catch (IllegalArgumentException e) {
                    logger.warn("Could not inject logger for class: " + bean.getClass(), e);
                } catch (IllegalAccessException e) {
                    logger.warn("Could not inject logger for class: " + bean.getClass(), e);
                }/*from  w ww  . j ava2 s .  c  om*/
            }
        }
    }

    return bean;
}

From source file:mil.army.usace.data.dataquery.utility.DefaultConverter.java

@Override
public Object convertType(Object obj, Field field) throws ClassNotFoundException, ConversionException {
    Class fieldParam = field.getType();
    if (obj == null)
        return null;
    else {/*from www. j  av a  2  s  . c  om*/
        if (fieldParam.isPrimitive()) {
            return obj;
        } else {
            return convertType(obj, fieldParam);
        }
    }
}

From source file:com.gemstone.gemfire.test.junit.rules.serializable.SerializableTestNameTest.java

@Test
public void fieldNameShouldExist() throws Exception {
    Field field = TestName.class.getDeclaredField(FIELD_NAME);
    assertThat(field.getType()).isEqualTo(String.class);
}

From source file:com.nonninz.robomodel.RoboModelCollection.java

public void save() {
    Field[] fields = getClass().getFields();
    for (Field f : fields) {
        try {//ww  w.j a  v a  2s.co m
            if (f.getType().isAssignableFrom(Collection.class)) {
                @SuppressWarnings("unchecked")
                Collection<? extends RoboModel> list = (Collection<? extends RoboModel>) f.get(this);
                if (list != null) {
                    for (RoboModel model : list) {
                        model.save();
                    }
                }
            }
            if (f.getType().isArray()) {
                RoboModel[] list = (RoboModel[]) f.get(this);
                if (list != null) {
                    for (RoboModel model : list) {
                        model.save();
                    }
                }
            }
        } catch (IllegalAccessException e) {
            Ln.d(e, "Error while accessing field %s", f.getName());
        }
    }
}

From source file:com.nonninz.robomodel.RoboModelCollection.java

void setContext(Context context) {
    Field[] fields = getClass().getFields();
    for (Field f : fields) {
        try {//from  ww  w.ja v a  2s .  c  om
            if (f.getType().isAssignableFrom(Collection.class)) {
                @SuppressWarnings("unchecked")
                Collection<? extends RoboModel> list = (Collection<? extends RoboModel>) f.get(this);
                if (list != null) {
                    for (RoboModel model : list) {
                        model.setContext(context);
                    }
                }
            }
            if (f.getType().isArray()) {
                RoboModel[] list = (RoboModel[]) f.get(this);
                if (list != null) {
                    for (RoboModel model : list) {
                        model.setContext(context);
                    }
                }
            }
        } catch (IllegalAccessException e) {
            Ln.d(e, "Error while accessing field %s", f.getName());
        }
    }
}

From source file:com.google.code.siren4j.util.ReflectionUtils.java

/**
 * Replaces field tokens with the actual value in the fields. The field types must be simple property types
 *
 * @param str/*from   ww w.j  av  a2s .c  o  m*/
 * @param fields info
 * @param parentMode
 * @param obj
 * @return
 * @throws Siren4JException
 */
public static String replaceFieldTokens(Object obj, String str, List<ReflectedInfo> fields, boolean parentMode)
        throws Siren4JException {
    Map<String, Field> index = new HashMap<String, Field>();
    if (StringUtils.isBlank(str)) {
        return str;
    }
    if (fields != null) {
        for (ReflectedInfo info : fields) {
            Field f = info.getField();
            if (f != null) {
                index.put(f.getName(), f);
            }
        }
    }
    try {
        for (String key : ReflectionUtils.getTokenKeys(str)) {
            if ((!parentMode && !key.startsWith("parent.")) || (parentMode && key.startsWith("parent."))) {
                String fieldname = key.startsWith("parent.") ? key.substring(7) : key;
                if (index.containsKey(fieldname)) {
                    Field f = index.get(fieldname);
                    if (f.getType().isEnum() || ArrayUtils.contains(propertyTypes, f.getType())) {
                        String replacement = "";
                        Object theObject = f.get(obj);
                        if (f.getType().isEnum()) {
                            replacement = theObject == null ? "" : ((Enum) theObject).name();
                        } else {
                            replacement = theObject == null ? "" : theObject.toString();
                        }
                        str = str.replaceAll("\\{" + key + "\\}", Matcher.quoteReplacement("" + replacement));
                    }
                }
            }
        }
    } catch (Exception e) {
        throw new Siren4JException(e);
    }
    return str;

}

From source file:no.digipost.api.xml.SchemasTest.java

@Test
public void allSchemasExist() throws Exception {
    for (Field field : Schemas.class.getFields()) {
        if (isStatic(field.getModifiers()) && Resource.class.isAssignableFrom(field.getType())) {
            Resource resource = (Resource) field.get(Schemas.class);
            assertTrue(resource + " must exist! (declared in " + Schemas.class.getName() + "." + field.getName()
                    + ")", resource.exists());
        }//w  w  w  .  j  av a 2s  .  c o m
    }
}

From source file:com.thoughtworks.xstream.benchmark.reflection.targets.AbstractReflectionTarget.java

protected void fill(final Object o) {
    final char[] zero = new char[8];
    Arrays.fill(zero, '0');
    for (Class cls = o.getClass(); cls != Object.class; cls = cls.getSuperclass()) {
        final Field[] fields = cls.getDeclaredFields();
        for (int i = 0; i < fields.length; i++) {
            final Field field = fields[i];
            field.setAccessible(true);//  www  . j a va2  s .  c  o  m
            if (field.getType() == String.class) {
                final String hex = Integer.toHexString(i);
                try {
                    field.set(o, new String(zero, 0, zero.length - hex.length()) + hex);
                } catch (final IllegalAccessException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}

From source file:com.holonplatform.core.internal.beans.DefaultBeanPropertySet.java

/**
 * Write the <code>property</code> value into given instance using given value, using BeanProperty configuration
 * write method or field, if available.//from  w w  w .  jav a 2  s. c  o m
 * @param property Property to write
 * @param value Value to write
 * @param instance Instance to write
 * @return Written value
 */
private static Object writeValue(BeanProperty<?> property, Object value, Object instance) {
    ObjectUtils.argumentNotNull(property, "Property must be not null");

    if (property.getWriteMethod().isPresent()) {
        try {
            property.getWriteMethod().get().invoke(instance, new Object[] {
                    getValueToWrite(property.getWriteMethod().get().getParameters()[0].getType(), value) });

            LOGGER.debug(() -> "BeanPropertySet: written property [" + property + "] value [" + value
                    + "] from instance [" + instance + "] using method [" + property.getWriteMethod() + "]");

        } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
            throw new PropertyWriteException(property,
                    "Cannot write property [" + property + "] value of type ["
                            + ((value != null) ? value.getClass().getName() : "null") + "] on bean instance ["
                            + instance + "]",
                    e);
        }
    } else {
        Field field = property.getField()
                .orElseThrow(() -> new PropertyReadException(property,
                        "No write method and no accessible field available to write property [" + property
                                + "] on bean class [" + instance.getClass().getName() + "]"));
        try {
            FieldUtils.writeField(field, instance, getValueToWrite(field.getType(), value), true);

            LOGGER.debug(() -> "BeanPropertySet: read property [" + property + "] value [" + value
                    + "] from instance [" + instance + "] using field [" + field + "]");

        } catch (IllegalAccessException e) {
            throw new PropertyWriteException(property, e);
        }
    }

    return value;
}

From source file:com.nabla.wapp.server.auth.AuthDatabase.java

public AuthDatabase(final String dbName, final ServletContext serverContext, final Class<?> roles,
        final String rootPassword) throws SQLException {
    super(dbName, serverContext);
    final Connection conn = this.getConnection();
    try {//from   ww w. j  a v  a 2  s .c o  m
        new UserManager(conn).initializeDatabase(new UserManager.IRoleListProvider() {
            @Override
            public Map<String, String[]> get() {
                final Map<String, String[]> rslt = new HashMap<String, String[]>();
                for (final Field field : roles.getFields()) {
                    if (!field.getType().getCanonicalName().equals(String.class.getName()))
                        continue;
                    try {
                        final String roleName = (String) field.get(null); // assume static
                        final IRole definition = field.getAnnotation(IRole.class);
                        if (definition == null) {
                            // privilege
                            rslt.put(roleName, null);
                        } else {
                            // role
                            rslt.put(roleName, definition.value());
                        }
                    } catch (final IllegalArgumentException e) {
                        if (log.isDebugEnabled())
                            log.debug("invalid field '" + field.getName() + "' as a role", e);
                    } catch (final IllegalAccessException e) {
                        if (log.isDebugEnabled())
                            log.debug("invalid field '" + field.getName() + "' as a role", e);
                    }
                }
                return rslt;
            }
        }, rootPassword);
    } finally {
        close(conn);
    }
}