Example usage for java.lang.reflect Field getClass

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

Introduction

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

Prototype

@HotSpotIntrinsicCandidate
public final native Class<?> getClass();

Source Link

Document

Returns the runtime class of this Object .

Usage

From source file:com.datatorrent.stram.plan.logical.LogicalPlan.java

public static Type getPortType(Field f) {
    if (f.getGenericType() instanceof ParameterizedType) {
        ParameterizedType t = (ParameterizedType) f.getGenericType();
        //LOG.debug("Field type is parameterized: " + Arrays.asList(t.getActualTypeArguments()));
        //LOG.debug("rawType: " + t.getRawType()); // the port class
        Type typeArgument = t.getActualTypeArguments()[0];
        if (typeArgument instanceof Class) {
            return typeArgument;
        } else if (typeArgument instanceof TypeVariable) {
            TypeVariable<?> tv = (TypeVariable<?>) typeArgument;
            LOG.debug("bounds: " + Arrays.asList(tv.getBounds()));
            // variable may contain other variables, java.util.Map<java.lang.String, ? extends T2>
            return tv.getBounds()[0];
        } else if (typeArgument instanceof GenericArrayType) {
            LOG.debug("type {} is of GenericArrayType", typeArgument);
            return typeArgument;
        } else if (typeArgument instanceof WildcardType) {
            LOG.debug("type {} is of WildcardType", typeArgument);
            return typeArgument;
        } else if (typeArgument instanceof ParameterizedType) {
            return typeArgument;
        } else {/*from w  w w.ja va 2s  . c o  m*/
            LOG.error("Type argument is of expected type {}", typeArgument);
            return null;
        }
    } else {
        // ports are always parameterized
        LOG.error("No type variable: {}, typeParameters: {}", f.getType(),
                Arrays.asList(f.getClass().getTypeParameters()));
        return null;
    }
}

From source file:org.apache.camel.dataformat.bindy.BindyCsvFactory.java

/**
 * /* ww  w.ja  v  a  2s .  com*/
 * Generate a table containing the data formated and sorted with their position/offset
 * If the model is Ordered than a key is created combining the annotation @Section and Position of the field
 * If a relation @OneToMany is defined, than we iterate recursivelu through this function
 * The result is placed in the Map<Integer, List> results
 * 
 * @param clazz
 * @param obj
 * @throws Exception
 */
private void generateCsvPositionMap(Class clazz, Object obj) throws Exception {

    String result = "";

    for (Field field : clazz.getDeclaredFields()) {

        field.setAccessible(true);

        DataField datafield = field.getAnnotation(DataField.class);

        if (datafield != null) {

            if (obj != null) {

                // Retrieve the format, pattern and precision associated to
                // the type
                Class type = field.getType();
                String pattern = datafield.pattern();
                int precision = datafield.precision();

                // Create format
                Format format = FormatFactory.getFormat(type, pattern, getLocale(), precision);

                // Get field value
                Object value = field.get(obj);

                result = formatString(format, value);

                if (LOG.isDebugEnabled()) {
                    LOG.debug("Value to be formatted : " + value + ", position : " + datafield.pos()
                            + ", and its formated value : " + result);
                }

            } else {
                result = "";
            }

            Integer key;

            if (isMessageOrdered()) {

                // Generate a key using the number of the section
                // and the position of the field
                Integer key1 = sections.get(obj.getClass().getName());
                Integer key2 = datafield.position();
                Integer keyGenerated = generateKey(key1, key2);

                if (LOG.isDebugEnabled()) {
                    LOG.debug("Key generated : " + String.valueOf(keyGenerated) + ", for section : " + key1);
                }

                key = keyGenerated;

            } else {

                key = datafield.pos();
            }

            if (!results.containsKey(key)) {

                List list = new LinkedList();
                list.add(result);
                results.put(key, list);

            } else {

                List list = (LinkedList) results.get(key);
                list.add(result);
            }

        }

        OneToMany oneToMany = field.getAnnotation(OneToMany.class);
        if (oneToMany != null) {

            // Set global variable
            // Will be used during generation of CSV
            isOneToMany = true;

            ArrayList list = (ArrayList) field.get(obj);

            if (list != null) {

                Iterator it = list.iterator();

                while (it.hasNext()) {

                    Object target = it.next();
                    generateCsvPositionMap(target.getClass(), target);

                }

            } else {

                // Call this function to add empty value
                // in the table
                generateCsvPositionMap(field.getClass(), null);
            }

        }
    }

}

From source file:it.grid.storm.config.Configuration.java

@Override
public String toString() {

    StringBuilder configurationStringBuilder = new StringBuilder();
    try {//from   w w  w  . j a  v a 2s. c  om
        // This class methods
        Method methods[] = Configuration.instance.getClass().getDeclaredMethods();

        // This class fields
        Field[] fields = Configuration.instance.getClass().getDeclaredFields();
        HashMap<String, String> methodKeyMap = new HashMap<String, String>();
        for (Field field : fields) {
            String fieldName = field.getName();
            if (fieldName.endsWith("KEY") && field.getType().equals(String.class)) {
                // from a field like GROUP_TAPE_WRITE_BUFFER_KEY =
                // "tape.buffer.group.write"
                // puts in the map the pair
                // <getgrouptapewritebuffer,tape.buffer.group.write>
                String mapKey = "get"
                        + fieldName.substring(0, fieldName.lastIndexOf("_")).replaceAll("_", "").toLowerCase();
                if (methodKeyMap.containsKey(mapKey)) {
                    String value = methodKeyMap.get(mapKey);
                    methodKeyMap.put(mapKey, value + " , " + (String) field.get(Configuration.instance));
                } else {
                    methodKeyMap.put(mapKey, (String) field.get(Configuration.instance));
                }
            }
        }

        Object field = null;
        Object[] dummyArray = new Object[0];
        for (Method method : methods) {
            /*
             * with method.getModifiers() == 1 we check that the method is public
             * (otherwise he can request real parameters)
             */
            if (method.getName().substring(0, 3).equals("get") && (!method.getName().equals("getInstance"))
                    && method.getModifiers() == 1) {
                field = method.invoke(Configuration.instance, dummyArray);
                if (field.getClass().isArray()) {
                    field = ArrayUtils.toString(field);
                }
                String value = methodKeyMap.get(method.getName().toLowerCase());
                if (value == null) {
                    configurationStringBuilder.insert(0,
                            "!! Unable to find method " + method.getName() + " in methode key map!");
                } else {
                    configurationStringBuilder.append("Property " + value + " : ");
                }
                if (field.getClass().equals(String.class)) {
                    field = '\'' + ((String) field) + '\'';
                }
                configurationStringBuilder.append(method.getName() + "() == " + field.toString() + "\n");
            }
        }
        return configurationStringBuilder.toString();
    } catch (Exception e) {
        if (e.getClass().isAssignableFrom(java.lang.reflect.InvocationTargetException.class)) {
            configurationStringBuilder.insert(0,
                    "!!! Cannot do toString! Got an Exception: " + e.getCause() + "\n");
        } else {
            configurationStringBuilder.insert(0, "!!! Cannot do toString! Got an Exception: " + e + "\n");
        }
        return configurationStringBuilder.toString();
    }
}

From source file:ca.oson.json.Oson.java

public Gson getGson() {
    if (gson == null) {
        GsonBuilder gsonBuilder = new GsonBuilder();

        switch (getDefaultType()) {
        case ALWAYS:
            gsonBuilder.serializeNulls();
            break;
        case NON_NULL:
            break;
        case NON_EMPTY:
            break;
        case DEFAULT:
            gsonBuilder.serializeNulls();
            break;
        default://from w  w  w  .  ja  v a 2s.  co m
            gsonBuilder.serializeNulls();
            break;
        }

        switch (getFieldNaming()) {
        case FIELD: // original field name: someField_name
            gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.IDENTITY);
            break;
        case LOWER: // somefield_name -> some_field_name
            gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
            break;
        case UPPER: //SOMEFIELD_NAME -> SomeFieldName
            gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE);
            break;
        case CAMELCASE: // someFieldName
            gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.IDENTITY);
            break;
        case UPPER_CAMELCASE: // SomeFieldName
            gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE);
            break;
        case UNDERSCORE_CAMELCASE: // some_Field_Name
            gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
            break;
        case UNDERSCORE_UPPER_CAMELCASE: // Some_Field_Name
            gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
            break;
        case UNDERSCORE_LOWER: // some_field_name
            gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
            break;
        case UNDERSCORE_UPPER: // SOME_FIELD_NAME
            gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
            break;
        case SPACE_CAMELCASE: // some Field Name
            gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE_WITH_SPACES);
            break;
        case SPACE_UPPER_CAMELCASE: // Some Field Name
            gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE_WITH_SPACES);
            break;
        case SPACE_LOWER: // some field name
            gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE_WITH_SPACES);
            break;
        case SPACE_UPPER: // SOME FIELD NAME
            gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE_WITH_SPACES);
            break;
        case DASH_CAMELCASE: // some-Field-Name
            gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_DASHES);
            break;
        case DASH_UPPER_CAMELCASE: // Some-Field-Name
            gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_DASHES);
            break;
        case DASH_LOWER: // some-field-name
            gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_DASHES);
            break;
        case DASH_UPPER: // SOME-FIELD-NAME
            gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_DASHES);
            break;
        default:
            gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.IDENTITY);
            break;
        }

        if (getPrettyPrinting() && getIndentation() > 0) {
            gsonBuilder.setPrettyPrinting();
        }

        gsonBuilder.setDateFormat(options.getSimpleDateFormat());

        Set<FieldMapper> mappers = getFieldMappers();
        Map<Class, ClassMapper> classMappers = getClassMappers();
        List<ExclusionStrategy> strategies = new ArrayList<>();
        if (mappers != null) {
            gsonBuilder.setFieldNamingStrategy(new FieldNamingStrategy() {
                @Override
                public String translateName(Field f) {
                    String fieldName = f.getName();
                    String serializedName = java2Json(f);
                    if (!fieldName.equalsIgnoreCase(serializedName)) {
                        // if null returned, this field is ignored
                        return serializedName;
                    }
                    return json2Java(f);
                }
            });

            for (FieldMapper mapper : mappers) {
                if (mapper.java == null || mapper.json == null || mapper.ignore) {
                    strategies.add(new ExclusionStrategy() {

                        @Override
                        public boolean shouldSkipField(FieldAttributes f) {
                            String name = f.getName();
                            Class cls = f.getClass();

                            if (mapper.java == null) {
                                if (mapper.json.equals(name)) {
                                    if (mapper.getType() == null || cls.equals(mapper.getType())) {
                                        return true;
                                    }
                                }

                            } else if (mapper.json == null || mapper.ignore) {
                                if (mapper.java.equals(name)) {
                                    if (mapper.getType() == null || cls.equals(mapper.getType())) {
                                        return true;
                                    }
                                }

                            }

                            return false;
                        }

                        @Override
                        public boolean shouldSkipClass(Class<?> clazz) {
                            return false;
                        }
                    });
                }
            }
        }

        if (classMappers != null) {
            for (Entry<Class, ClassMapper> entry : classMappers.entrySet()) {
                ClassMapper mapper = entry.getValue();
                if (mapper.getType() == null) {
                    mapper.setType(entry.getKey());
                }
                if (mapper.ignore != null && mapper.ignore) {
                    strategies.add(new ExclusionStrategy() {

                        @Override
                        public boolean shouldSkipField(FieldAttributes f) {
                            return false;
                        }

                        @Override
                        public boolean shouldSkipClass(Class<?> clazz) {
                            if (clazz.equals(mapper.getType())) {
                                return true;
                            }
                            return false;
                        }
                    });
                }
            }

            for (Entry<Class, ClassMapper> entry : classMappers.entrySet()) {
                ClassMapper mapper = entry.getValue();
                if (!mapper.ignore && mapper.constructor != null) {
                    gsonBuilder.registerTypeAdapter(entry.getKey(), mapper.constructor);
                }
            }
        }

        int size = strategies.size();
        if (size > 0) {
            gsonBuilder.setExclusionStrategies(strategies.toArray(new ExclusionStrategy[size]));
        }

        Double version = getVersion();
        if (version != null) {
            gsonBuilder.setVersion(version);
        }

        if (isUseGsonExpose()) {
            gsonBuilder.excludeFieldsWithoutExposeAnnotation();
        }

        if (!DefaultValue.isDefault(getPatterns())) {
            gsonBuilder.setLenient();
        }

        gson = gsonBuilder.create();
    }

    return gson;
}