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.qingstor.sdk.utils.QSJSONUtil.java

private static boolean initParameter(JSONObject o, Field[] declaredField, Class objClass, Object targetObj)
        throws NoSuchMethodException {
    boolean hasParam = false;
    for (Field field : declaredField) {
        String methodField = QSParamInvokeUtil.capitalize(field.getName());
        String getMethodName = field.getType() == Boolean.class ? "is" + methodField : "get" + methodField;
        String setMethodName = "set" + methodField;
        Method[] methods = objClass.getDeclaredMethods();
        for (Method m : methods) {
            if (m.getName().equals(getMethodName)) {
                ParamAnnotation annotation = m.getAnnotation(ParamAnnotation.class);
                if (annotation == null) {
                    continue;
                }//from www. j a  v a  2 s  .c o m
                String dataKey = annotation.paramName();

                if (o.has(dataKey)) {
                    hasParam = true;
                    Object data = toObject(o, dataKey);
                    Method setM = objClass.getDeclaredMethod(setMethodName, field.getType());
                    setParameterToMap(setM, targetObj, field, data);
                }
            }
        }
    }
    return hasParam;
}

From source file:com.diversityarrays.dal.db.DalDatabaseUtil.java

static public void addEntityFields(Class<? extends DalEntity> entityClass, DalResponseBuilder responseBuilder) {

    responseBuilder.addResponseMeta("SCol");

    for (Field fld : entityClass.getDeclaredFields()) {
        if (!Modifier.isStatic(fld.getModifiers())) {
            Column column = fld.getAnnotation(Column.class);
            if (column != null) {

                DalResponseBuilder builder = responseBuilder.startTag("SCol");

                builder.attribute("Required", column.nullable() ? "0" : "1");

                int colSize = 11;
                Class<?> fieldType = fld.getType();
                if (String.class == fieldType) {
                    colSize = column.length();
                }/*from w w  w .j  a  va 2 s  .c  om*/
                builder.attribute("ColSize", Integer.toString(colSize));

                builder.attribute("Description", "");

                builder.attribute("Name", column.name());

                // TODO Synchronise with the Perl DAL code
                builder.attribute("DataType", fieldType.getSimpleName().toLowerCase());

                builder.endTag();
            }
        }
    }
}

From source file:lapin.load.Loader.java

static private Object _impSymbols(Class clazz, Object export, Env env) throws IllegalAccessException {
    Lisp lisp = env.lisp();//w  w w  . j  a  v  a  2s. com
    Field[] fields = clazz.getFields();
    Class symClass = Symbol.class;
    for (int i = 0; i < fields.length; i++) {
        Field f = fields[i];
        int m = f.getModifiers();
        if (!Modifier.isStatic(m))
            continue;
        if (!symClass.isAssignableFrom(f.getType()))
            continue;
        Symbol sym = Data.symbol(f.get(null));
        lisp.getObarray().imp(sym.pkg(), sym);
        if (!Data.isNot(export))
            lisp.getObarray().exp(sym.pkg(), sym);
    }
    return Symbols.T;
}

From source file:com.stratio.deep.es.utils.UtilES.java

/**
 * converts from an entity class with deep's anotations to JSONObject.
 *
 * @param t   an instance of an object of type T to convert to JSONObject.
 * @param <T> the type of the object to convert.
 * @return the provided object converted to JSONObject.
 * @throws IllegalAccessException/*ww  w  .  j  av a2  s  .co  m*/
 * @throws InstantiationException
 * @throws InvocationTargetException
 */
public static <T> JSONObject getJsonFromObject(T t)
        throws IllegalAccessException, InstantiationException, InvocationTargetException {
    Field[] fields = AnnotationUtils.filterDeepFields(t.getClass());

    JSONObject json = new JSONObject();

    for (Field field : fields) {
        Method method = Utils.findGetter(field.getName(), t.getClass());
        Object object = method.invoke(t);
        if (object != null) {
            if (Collection.class.isAssignableFrom(field.getType())) {
                Collection c = (Collection) object;
                Iterator iterator = c.iterator();
                List<JSONObject> innerJsonList = new ArrayList<>();

                while (iterator.hasNext()) {
                    innerJsonList.add(getJsonFromObject((IDeepType) iterator.next()));
                }
                json.put(AnnotationUtils.deepFieldName(field), innerJsonList);
            } else if (IDeepType.class.isAssignableFrom(field.getType())) {
                json.put(AnnotationUtils.deepFieldName(field), getJsonFromObject((IDeepType) object));
            } else {
                json.put(AnnotationUtils.deepFieldName(field), object);
            }
        }
    }

    return json;
}

From source file:com.stratio.deep.es.utils.UtilES.java

/**
 * converts from an entity class with deep's anotations to JSONObject.
 *
 * @param t   an instance of an object of type T to convert to JSONObject.
 * @param <T> the type of the object to convert.
 * @return the provided object converted to JSONObject.
 * @throws IllegalAccessException//  ww  w . java  2  s  . c  o m
 * @throws InstantiationException
 * @throws InvocationTargetException
 */
public static <T> LinkedMapWritable getLinkedMapWritableFromObject(T t)
        throws IllegalAccessException, InstantiationException, InvocationTargetException {
    Field[] fields = AnnotationUtils.filterDeepFields(t.getClass());

    LinkedMapWritable linkedMapWritable = new LinkedMapWritable();

    for (Field field : fields) {
        Method method = Utils.findGetter(field.getName(), t.getClass());
        Object object = method.invoke(t);
        if (object != null) {
            if (Collection.class.isAssignableFrom(field.getType())) {
                Collection c = (Collection) object;
                Iterator iterator = c.iterator();
                List<LinkedMapWritable> innerJsonList = new ArrayList<>();

                while (iterator.hasNext()) {
                    innerJsonList.add(getLinkedMapWritableFromObject((IDeepType) iterator.next()));
                }
                // linkedMapWritable.put(new Text(AnnotationUtils.deepFieldName(field)), new
                // LinkedMapWritable[innerJsonList.size()]);
            } else if (IDeepType.class.isAssignableFrom(field.getType())) {
                linkedMapWritable.put(new Text(AnnotationUtils.deepFieldName(field)),
                        getLinkedMapWritableFromObject((IDeepType) object));
            } else {
                linkedMapWritable.put(new Text(AnnotationUtils.deepFieldName(field)),
                        getWritableFromObject(object));
            }
        }
    }

    return linkedMapWritable;
}

From source file:com.impetus.kundera.metadata.MetadataUtils.java

/**
 * Checks whether a given field is Element collection field of BASIC type
 * //w  w  w  .  j ava 2s  .  co  m
 * @param collectionField
 * @return
 */
public static boolean isBasicElementCollectionField(Field collectionField) {
    if (!Collection.class.isAssignableFrom(collectionField.getType())
            && !Map.class.isAssignableFrom(collectionField.getType())) {
        return false;
    }

    List<Class<?>> genericClasses = PropertyAccessorHelper.getGenericClasses(collectionField);
    for (Class genericClass : genericClasses) {
        if (genericClass.getAnnotation(Embeddable.class) != null) {
            return false;
        }
    }
    return true;
}

From source file:com.spectralogic.ds3contractcomparator.print.htmlprinter.generators.row.ModifiedHtmlRowGenerator.java

/**
 * Recursively traverses two objects using reflection and constructs the modified
 * rows that represent the changes and differences between the objects.
 *//* ww w . ja v  a  2  s . c  o m*/
public static <T> ImmutableList<Row> createModifiedRows(final T oldObject, final T newObject,
        final int indent) {
    if (oldObject == null && newObject == null) {
        return ImmutableList.of();
    }
    final Field[] fields = getFields(oldObject, newObject);
    final ImmutableList.Builder<Row> builder = ImmutableList.builder();

    for (final Field field : fields) {
        final String property = field.getName();

        final Optional<String> oldValue = getPropertyValue(oldObject, property);
        final Optional<String> newValue = getPropertyValue(newObject, property);

        if (oldValue.isPresent() || newValue.isPresent()) {
            final int fieldIndent = toModifiedFieldIndent(indent, oldObject, newObject, field);
            if (field.getType() == ImmutableList.class) {
                //Field is a list, recursively print each element in the list
                builder.add(new NoChangeRow(fieldIndent, property, ""));

                final ImmutableList<Object> oldObjList = getListPropertyFromObject(field, oldObject);
                final ImmutableList<Object> newObjList = getListPropertyFromObject(field, newObject);

                if (hasContent(oldObjList) || hasContent(newObjList)) {
                    final String uniqueProperty = getPropertyNameFromList(oldObjList, newObjList);

                    final ImmutableSet<String> parameterUnion = toPropertyUnion(oldObjList, newObjList,
                            uniqueProperty);
                    final ImmutableMap<String, Object> oldMap = toPropertyMap(oldObjList, uniqueProperty);
                    final ImmutableMap<String, Object> newMap = toPropertyMap(newObjList, uniqueProperty);

                    parameterUnion.forEach(param -> builder
                            .addAll(createModifiedRows(oldMap.get(param), newMap.get(param), fieldIndent + 1)));
                }
            } else if (oldValue.isPresent() && newValue.isPresent() && oldValue.get().equals(newValue.get())) {
                //Element is the same in both contracts
                builder.add(new NoChangeRow(fieldIndent, property, oldValue.get()));
            } else {
                //Element is different between old and new contracts
                builder.add(new ModifiedRow(fieldIndent, property, oldValue.orElse(RowConstants.NA),
                        newValue.orElse(RowConstants.NA)));
            }
        }
    }
    return builder.build();
}

From source file:lapin.load.Loader.java

static private Object _impSubrs(Object pkgname, Class clazz, Symbol indicator, Object export, Env env)
        throws IllegalAccessException {
    Lisp lisp = env.lisp();/*from w w  w  . j a va  2  s .c o  m*/
    Field[] fields = clazz.getFields();
    Class subrClass = Subr.class;
    for (int i = 0; i < fields.length; i++) {
        Field f = fields[i];
        int m = f.getModifiers();
        if (!Modifier.isStatic(m))
            continue;
        if (!subrClass.isAssignableFrom(f.getType()))
            continue;
        Subr subr = Data.subr(f.get(null));
        Symbol sym = Data.symbol(lisp.getObarray().intern(pkgname, subr.name()).nth(0));
        if (!Data.isNot(export))
            lisp.getObarray().exp(pkgname, sym);
        Object old = lisp.getProp(sym, indicator, Symbols.NIL);
        if (!Data.isNot(old))
            throw new LispException(
                    "conflict detected while importing subrs " + "defined in ~S: name=~S indicator=~S",
                    Lists.list(clazz, sym, indicator));
        lisp.setProp(sym, indicator, subr);
        if (subr instanceof Prop)
            lisp.setProp((Prop) subr, SysSymbols.SUBR_FIELD, f);
    }
    return Symbols.T;
}

From source file:at.ac.tuwien.infosys.jcloudscale.utility.ReflectionUtil.java

public static void checkLegalCloudIdDef(Object obj) {

    for (Field f : obj.getClass().getDeclaredFields()) {
        if (f.getAnnotation(CloudObjectId.class) != null) {

            if (!f.getType().equals(UUID.class) && !f.getType().equals(String.class)
                    && !f.getType().equals(Object.class))
                throw new IllegalDefinitionException("Illegal field type " + f.getType().getName()
                        + " annotated with "
                        + "@CloudObjectId. You may only annotate java.lang.Object, java.lang.String and java.util.UUID");

            if (Modifier.isStatic(f.getModifiers()))
                throw new IllegalDefinitionException("Illegal field " + f.getName()
                        + " annotated with @CloudObjectId. " + "Field has to be non-static.");

        }/*from   w  ww  .jav  a2 s.c om*/
    }

}

From source file:com.doitnext.jsonschema.generator.SchemaGen.java

private static boolean handleProperties(Class<?> classz, StringBuilder sb, Map<String, String> declarations,
        String uriPrefix) {//w w w. ja v a2  s .c  om
    boolean result = false;
    String prepend = "";
    Set<String> processedFields = new HashSet<String>();
    sb.append("{");
    for (Field field : classz.getFields()) {
        JsonSchemaProperty propertyDecl = field.getAnnotation(JsonSchemaProperty.class);
        if (propertyDecl != null) {
            Class<?> propClassz = field.getType();
            StringBuilder sb2 = new StringBuilder();
            boolean inline = true;
            sb2.append("{");
            if (!handleSimpleType(propClassz, sb2, propertyDecl, declarations, uriPrefix)) {
                if (!handleArrayType(propClassz, sb2, propertyDecl, declarations, uriPrefix)) {
                    inline = false;
                }
            }
            sb2.append("}");
            if (inline) {
                sb.append(prepend);
                sb.append("\"");
                sb.append(propertyDecl.name());
                sb.append("\":");
                sb.append(sb2.toString());
                prepend = ", ";
            } else {
                String id = null;
                JsonSchemaClass jsc = propClassz.getAnnotation(JsonSchemaClass.class);
                if (jsc != null)
                    id = jsc.id();
                else
                    id = propClassz.getName();
                declarations.put(id, sb2.toString());

                sb.append(prepend);
                sb.append("\"");
                sb.append(propertyDecl.name());
                sb.append("\":{\"$ref\":\"");
                if (!StringUtils.isEmpty(uriPrefix))
                    sb.append(uriPrefix);
                sb.append(id);
                sb.append("\"}");
                prepend = ", ";
            }
            processedFields.add(propertyDecl.name());
        }
    }
    for (Method method : classz.getMethods()) {
        JsonSchemaProperty propertyDecl = method.getAnnotation(JsonSchemaProperty.class);
        if (propertyDecl != null && !processedFields.contains(propertyDecl.name())) {
            Class<?> propClassz = method.getReturnType();
            StringBuilder sb2 = new StringBuilder();
            boolean inline = true;
            sb2.append("{");
            if (!handleSimpleType(propClassz, sb2, propertyDecl, declarations, uriPrefix)) {
                if (!handleArrayType(propClassz, sb2, propertyDecl, declarations, uriPrefix)) {
                    inline = false;
                }
            }
            sb2.append("}");
            if (inline) {
                sb.append(prepend);
                sb.append("\"");
                sb.append(propertyDecl.name());
                sb.append("\":");
                sb.append(sb2.toString());
                prepend = ", ";
            } else {
                String id = null;
                JsonSchemaClass jsc = propClassz.getAnnotation(JsonSchemaClass.class);
                if (jsc != null)
                    id = jsc.id();
                else
                    id = propClassz.getName();
                declarations.put(id, sb2.toString());

                sb.append(prepend);
                sb.append("\"");
                sb.append(propertyDecl.name());
                sb.append("\":{\"$ref\":\"");
                if (!StringUtils.isEmpty(uriPrefix))
                    sb.append(uriPrefix);
                sb.append(id);
                sb.append("\"}");
                prepend = ", ";
            }
            processedFields.add(propertyDecl.name());
        }
    }
    sb.append("}");
    return result;
}