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.facebook.presto.hive.s3.TestPrestoS3FileSystem.java

@SuppressWarnings("unchecked")
private static <T> T getFieldValue(Object instance, Class<?> clazz, String name, Class<T> type) {
    try {//w w w .  j av  a2  s .  c  o m
        Field field = clazz.getDeclaredField(name);
        checkArgument(field.getType() == type, "expected %s but found %s", type, field.getType());
        field.setAccessible(true);
        return (T) field.get(instance);
    } catch (ReflectiveOperationException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.lonepulse.robozombie.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>
 * /* ww w .  j a v a  2  s  .c  om*/
 * <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) {

                    Log.e(Zombie.class.getName(),
                            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:spring.osgi.utils.OsgiBundleUtils.java

/**
 * Returns the underlying BundleContext for the given Bundle. This uses
 * reflection and highly dependent of the OSGi implementation. Should not be
 * used if OSGi 4.1 is being used./*from   w  ww.j  av a2s. c  o  m*/
 *
 * @param bundle OSGi bundle
 * @return the bundle context for this bundle
 */
public static BundleContext getBundleContext(final Bundle bundle) {
    if (bundle == null)
        return null;

    // try Equinox getContext
    Method meth = ReflectionUtils.findMethod(bundle.getClass(), "getContext", new Class[0]);

    // fallback to getBundleContext (OSGi 4.1)
    if (meth == null)
        meth = ReflectionUtils.findMethod(bundle.getClass(), "getBundleContext", new Class[0]);

    final Method m = meth;

    if (meth != null) {
        ReflectionUtils.makeAccessible(meth);
        return (BundleContext) ReflectionUtils.invokeMethod(m, bundle);
    }

    // fallback to field inspection (KF and Prosyst)
    final BundleContext[] ctx = new BundleContext[1];

    ReflectionUtils.doWithFields(bundle.getClass(), new FieldCallback() {

        public void doWith(final Field field) throws IllegalArgumentException, IllegalAccessException {
            ReflectionUtils.makeAccessible(field);
            ctx[0] = (BundleContext) field.get(bundle);
        }
    }, new FieldFilter() {

        public boolean matches(Field field) {
            return BundleContext.class.isAssignableFrom(field.getType());
        }
    });

    return ctx[0];
}

From source file:io.apiman.plugins.keycloak_oauth_policy.ClaimLookup.java

private static void getProperties(Class<?> klazz, String path, Deque<Field> fieldChain) {
    for (Field f : klazz.getDeclaredFields()) {
        f.setAccessible(true);// w w  w .j a  v  a2 s.  com
        JsonProperty jsonProperty = f.getAnnotation(JsonProperty.class);
        if (jsonProperty != null) {
            fieldChain.push(f);
            // If the inspected type has nested @JsonProperty annotations, we need to inspect it
            if (hasJsonPropertyAnnotation(f)) {
                getProperties(f.getType(), f.getName() + ".", fieldChain); // Add "." when traversing into new object.
            } else { // Otherwise, just assume it's simple as the best we can do is #toString
                List<Field> fieldList = new ArrayList<>(fieldChain);
                Collections.reverse(fieldList);
                STANDARD_CLAIMS_FIELD_MAP.put(path + jsonProperty.value(), fieldList);
                fieldChain.pop(); // Pop, as we have now reached end of this chain.
            }
        }
    }
}

From source file:org.appverse.web.framework.backend.api.converters.helpers.ConverterUtils.java

/**
 * Copy source bean properties of type bean to target bean as detached beans
 * //from   ww  w. java2s  .c om
 * @param sourceBean
 *            Source Bean
 * @param targetBean
 *            Target Bean
 * @param childrenBeanConverters
 *            List of converters needed to convert source bean children of
 *            type bean to target bean children of type bean
 * @param sourceFields
 *            Fields of source Bean
 * @throws Exception
 */
private static void convertBeanFields(AbstractBean sourceBean, AbstractBean targetBean,
        IBeanConverter[] childrenBeanConverters, Field[] sourceFields) throws Exception {

    // Arrays to hold bean field names, source types and target types
    String[] beanFieldNames = new String[0];
    Type[] sourceFieldTypes = new Type[0];
    Type[] targetFieldTypes = new Type[0];

    // For each source field...
    for (Field field : sourceFields) {
        // If source field is a bean...
        if (AbstractBean.class.isAssignableFrom(field.getType())) {
            // Fill Arrays with name, source field type and target type
            beanFieldNames = (String[]) ArrayUtils.add(beanFieldNames, field.getName());

            sourceFieldTypes = (Type[]) ArrayUtils.add(sourceFieldTypes, field.getType());

            targetFieldTypes = (Type[]) ArrayUtils.add(targetFieldTypes,
                    targetBean.getClass().getDeclaredField(field.getName()).getType());
        }
    }

    // For each field with bean type...
    for (int i = 0; i < beanFieldNames.length; i++) {
        String beanFieldName = beanFieldNames[i];
        Type sourceFieldType = sourceFieldTypes[i];
        Type targetFieldType = targetFieldTypes[i];

        // Select the proper converter...
        IBeanConverter converter = getConverter(childrenBeanConverters, sourceFieldType, targetFieldType);

        // Get the target bean constructor
        @SuppressWarnings("unchecked")
        Constructor<AbstractBean> constructor = ((Class<AbstractBean>) targetFieldType)
                .getConstructor(new Class[] {});
        // Create target child bean
        AbstractBean targetChildBean = constructor.newInstance(new Object[] {});
        // Detach target child bean with source child bean and converter
        ((Detachable) targetChildBean).detach(
                (AbstractBean) getGetterMethod(beanFieldName, sourceBean).invoke(sourceBean), converter);
        // Set the detached target bean
        getSetterMethod(beanFieldName, targetFieldType, targetBean).invoke(targetBean, targetChildBean);

    }
}

From source file:com.adobe.acs.commons.mcp.util.AnnotatedFieldDeserializer.java

private static void parseInputList(Object target, String[] values, Field field)
        throws ReflectiveOperationException, ParseException {
    List convertedValues = new ArrayList();
    Class type = getCollectionComponentType(field);
    for (String value : values) {
        Object val = convertValue(value, type);
        convertedValues.add(val);
    }/*  ww  w .j a v a2s.  c  om*/
    if (field.getType().isArray()) {
        Object array = Array.newInstance(field.getType().getComponentType(), convertedValues.size());
        for (int i = 0; i < convertedValues.size(); i++) {
            Array.set(array, i, convertedValues.get(i));
        }
        FieldUtils.writeField(field, target, array, true);
    } else {
        Collection c = (Collection) getInstantiatableListType(field.getType()).newInstance();
        c.addAll(convertedValues);
        FieldUtils.writeField(field, target, c, true);
    }
}

From source file:com.dungnv.vfw5.base.utils.StringUtils.java

public static void escapeHTMLString(Object escapeObject) {
    String oldData = "";
    String newData = "";
    try {//from   w  ww.  j  a v a 2 s.c  o m
        if (escapeObject != null) {
            Class escapeClass = escapeObject.getClass();
            Field fields[] = escapeClass.getDeclaredFields();
            Field superFields[] = escapeClass.getSuperclass().getDeclaredFields();
            Field allField[] = new Field[fields.length + superFields.length];
            System.arraycopy(fields, 0, allField, 0, fields.length);
            System.arraycopy(superFields, 0, allField, fields.length, superFields.length);
            for (Field f : allField) {
                f.setAccessible(true);
                if (f.getType().equals(java.lang.String.class) && !Modifier.isFinal(f.getModifiers())) {
                    if (f.get(escapeObject) != null) {
                        oldData = f.get(escapeObject).toString();
                        newData = StringEscapeUtils.escapeSql(oldData);
                        f.set(escapeObject, newData);
                    }
                } else if (f.getType().isArray()) {
                    if (f.getType().getComponentType().equals(java.lang.String.class)) {
                        String[] tmpArr = (String[]) f.get(escapeObject);
                        if (tmpArr != null) {
                            for (int i = 0; i < tmpArr.length; i++) {
                                tmpArr[i] = StringEscapeUtils.escapeSql(tmpArr[i]);
                            }
                            f.set(escapeObject, tmpArr);
                        }
                    }
                } else if (f.get(escapeObject) instanceof List) {
                    List<Object> tmpList = (List<Object>) f.get(escapeObject);
                    for (int i = 0; i < tmpList.size(); i++) {
                        if (tmpList.get(i) instanceof java.lang.String) {
                            tmpList.set(i, StringEscapeUtils.escapeSql(tmpList.get(i).toString()));
                        }
                    }
                    f.set(escapeObject, tmpList);
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.dungnv.vfw5.base.utils.StringUtils.java

public static void trimString(Object obj, boolean isLower) {
    String oldData = "";
    String newData = "";
    try {// w w  w .j a v a2 s  .com
        if (obj != null) {
            Class escapeClass = obj.getClass();
            Field fields[] = escapeClass.getDeclaredFields();
            Field superFields[] = escapeClass.getSuperclass().getDeclaredFields();
            Field allField[] = new Field[fields.length + superFields.length];
            System.arraycopy(fields, 0, allField, 0, fields.length);
            System.arraycopy(superFields, 0, allField, fields.length, superFields.length);
            for (Field f : allField) {
                f.setAccessible(true);
                if (f.getType().equals(java.lang.String.class) && !Modifier.isFinal(f.getModifiers())) {
                    if (f.get(obj) != null) {
                        oldData = f.get(obj).toString();
                        newData = isLower ? oldData.trim().toLowerCase() : oldData.trim();
                        f.set(obj, newData);
                    }
                } else if (f.getType().isArray()) {
                    if (f.getType().getComponentType().equals(java.lang.String.class)) {
                        String[] tmpArr = (String[]) f.get(obj);
                        if (tmpArr != null) {
                            for (int i = 0; i < tmpArr.length; i++) {
                                tmpArr[i] = isLower ? tmpArr[i].trim().toLowerCase() : tmpArr[i].trim();
                            }
                            f.set(obj, tmpArr);
                        }
                    }
                } else if (f.get(obj) instanceof List) {
                    List<Object> tmpList = (List<Object>) f.get(obj);
                    for (int i = 0; i < tmpList.size(); i++) {
                        if (tmpList.get(i) instanceof java.lang.String) {
                            tmpList.set(i, isLower ? tmpList.get(i).toString().trim().toLowerCase()
                                    : tmpList.get(i).toString().trim());
                        }
                    }
                    f.set(obj, tmpList);
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:io.github.eternalbits.compactvd.CompactVD.java

private static void dump(Object obj, String in) {
    for (Field fld : obj.getClass().getDeclaredFields()) {
        try {/*from  w ww.ja va2 s  . c o  m*/
            if (!Modifier.isPrivate(fld.getModifiers())) {
                if (fld.getAnnotation(Deprecated.class) == null) {
                    if (!fld.getType().isAssignableFrom(List.class)) {
                        System.out.println(in + fld.getName() + ": " + fld.get(obj));
                    } else {
                        int i = 0;
                        for (Object item : (List<?>) fld.get(obj)) {
                            System.out.println(in + fld.getName() + "[" + i + "]");
                            dump(item, in + "    ");
                            i++;
                        }
                    }
                }
            }
        } catch (IllegalArgumentException | IllegalAccessException e) {
            e.printStackTrace();
        }
    }
}

From source file:com.ms.commons.test.common.ReflectUtil.java

public static boolean isValueEqualsBean(Object bean, String field, Object value) {
    Class<?> clazz = bean.getClass();
    try {/*from  www. j  a v a  2s . c o  m*/
        Field f = getDeclaredField(clazz, NamingUtil.dbNameToJavaName(field));
        f.setAccessible(true);
        try {
            Object beanValue = f.get(bean);
            Object fieldValue = TypeConvertUtil.convert(f.getType(), value);
            return CompareUtil.isObjectEquals(beanValue, fieldValue);
        } catch (IllegalArgumentException e) {
            throw new UnknowException(e);
        } catch (IllegalAccessException e) {
            throw new UnknowException(e);
        }
    } catch (SecurityException e) {
        throw new UnknowException(e);
    } catch (NoSuchFieldException e) {
        throw new JavaFieldNotFoundException(clazz, field);
    }
}