Example usage for java.lang.reflect Field getGenericType

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

Introduction

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

Prototype

public Type getGenericType() 

Source Link

Document

Returns a Type object that represents the declared type for the field represented by this Field object.

Usage

From source file:es.caib.sgtsic.utils.ejb.AbstractService.java

public boolean borrable(Object id) {

    T item = this.find(id);

    log.debug("Entramos a borrable " + item);

    if (item == null) {
        return false;
    }/*  w  ww. j  av a2s. com*/

    log.debug("Entramos a borrable con no false " + item);

    for (Field f : entityClass.getDeclaredFields()) {
        boolean hasToManyAnnotations = (f.isAnnotationPresent(OneToMany.class))
                || (f.isAnnotationPresent(ManyToMany.class));
        if (hasToManyAnnotations) {

            Type type = f.getGenericType();
            ParameterizedType pt = (ParameterizedType) type;

            List<Type> arguments = Arrays.asList(pt.getActualTypeArguments());

            Class childEntityClass = null;

            for (Type argtype : arguments) {
                childEntityClass = (Class) argtype;
                break;
            }

            if (childEntityClass == null) {
                continue;
            }

            if (this.childrenCount(id, childEntityClass, entityClass) > 0) {

                log.debug("Cuenta positiva");

                return false;
            }
        }
    }

    log.debug("Cuenta 0");

    return true;

}

From source file:com.logsniffer.util.value.ConfigInjector.java

@Override
public Object postProcessBeforeInitialization(final Object bean, final String beanName) throws BeansException {
    ReflectionUtils.doWithFields(bean.getClass(), new FieldCallback() {
        @Override//ww  w .  j av a2  s .  co  m
        public void doWith(final Field field) throws IllegalArgumentException, IllegalAccessException {
            LOGGER.debug("Injecting value={} for bean={}", field.getName(), beanName);
            field.setAccessible(true);
            final String key = field.getAnnotation(Configured.class).value();
            final String defaultValue = field.getAnnotation(Configured.class).defaultValue();
            final Class<?> targetValueType = (Class<?>) ((ParameterizedType) field.getGenericType())
                    .getActualTypeArguments()[0];
            field.set(bean, new ConfigValue<Object>() {
                private String oldTextValue;
                private Object oldValue;

                @Override
                public Object get() {
                    String textValue = getSource().getValue(key);
                    if (textValue == null) {
                        textValue = defaultValue;
                    }
                    if (oldTextValue != null && oldTextValue.equals(textValue)) {
                        return oldValue;
                    } else {
                        oldValue = conversionService.convert(textValue, targetValueType);
                        oldTextValue = textValue;
                        return oldValue;
                    }
                }
            });

        }
    }, new FieldFilter() {
        @Override
        public boolean matches(final Field field) {
            return field.getType().equals(ConfigValue.class) && field.isAnnotationPresent(Configured.class);
        }
    });

    return bean;
}

From source file:org.polymap.model2.store.geotools.FeatureStoreAdapter.java

public void init(StoreRuntimeContext _context) {
    this.context = _context;
    EntityRepository repo = context.getRepository();

    // check/create/update schemas
    if (createOrUpdateSchemas.get()) {
        //        FeatureStoreUnitOfWork uow = (FeatureStoreUnitOfWork)createUnitOfWork();
        for (Class<? extends Entity> entityClass : repo.getConfig().entities.get()) {

            // is entityClass complex?
            boolean isComplex = false;
            Class superClass = entityClass;
            for (; superClass != null; superClass = superClass.getSuperclass()) {
                for (Field field : superClass.getDeclaredFields()) {
                    if (CollectionProperty.class.isAssignableFrom(field.getType())) {
                        isComplex = true;
                        break;
                    }// ww w.  j  a v  a  2  s  .  co  m
                    if (Property.class.isAssignableFrom(field.getType())) {
                        Class binding = (Class) ((ParameterizedType) field.getGenericType())
                                .getActualTypeArguments()[0];
                        if (Composite.class.isAssignableFrom(binding)) {
                            isComplex = true;
                            break;
                        }
                    }
                }
            }

            // check/update schema            
            FeatureType entitySchema = isComplex ? featureType(entityClass) : simpleFeatureType(entityClass);
            try {
                log.info("Checking FeatureSource: " + entitySchema.getName().getLocalPart() + " ...");
                FeatureSource fs = store.getFeatureSource(entitySchema.getName());
                // update
                if (fs != null && !entitySchema.equals(fs.getSchema())) {
                    try {
                        log.warn("FeatureType has been changed: " + entitySchema.getName() + " !!!");
                        store.updateSchema(entitySchema.getName(), entitySchema);
                    } catch (UnsupportedOperationException e) {
                        log.warn("", e);
                    }
                }
            }
            // create schema
            // fs.getSchema() throws RuntimeException for ShapefileDataSource
            catch (Exception e) {
                try {
                    log.info("No feature store found: " + e.getLocalizedMessage() + ". Creating schema: "
                            + entitySchema);
                    store.createSchema(entitySchema);
                } catch (IOException e1) {
                    throw new ModelRuntimeException(e1);
                }
            }
        }
    }
}

From source file:com.qmetry.qaf.automation.ui.webdriver.ElementFactory.java

@SuppressWarnings("unchecked")
private boolean isDecoratable(Field field) {
    if (!hasAnnotation(field, com.qmetry.qaf.automation.ui.annotations.FindBy.class, FindBy.class,
            FindBys.class)) {
        return false;
    }/*from   w w  w  .j av  a 2 s.  c o  m*/
    if (WebElement.class.isAssignableFrom(field.getType())) {
        return true;
    }
    if (!(List.class.isAssignableFrom(field.getType()))) {
        return false;
    }
    Type genericType = field.getGenericType();
    if (!(genericType instanceof ParameterizedType)) {
        return false;
    }
    Type listType = ((ParameterizedType) genericType).getActualTypeArguments()[0];

    return WebElement.class.isAssignableFrom((Class<?>) listType);
}

From source file:com.github.rvesse.airline.Accessor.java

public Accessor(List<Field> path) {
    if (path == null)
        throw new NullPointerException("path is null");
    if (path.size() == 0)
        throw new IllegalArgumentException("path is empty");

    this.path = ListUtils.unmodifiableList(path);
    StringBuilder nameBuilder = new StringBuilder();

    // Build the name for the accessor
    nameBuilder.append(this.path.get(0).getDeclaringClass().getSimpleName());
    for (Field field : this.path) {
        nameBuilder.append('.').append(field.getName());
    }//from w w w  .  j  a  va  2  s. co m
    this.name = nameBuilder.toString();

    Field field = this.path.get(this.path.size() - 1);
    multiValued = Collection.class.isAssignableFrom(field.getType());
    javaType = getItemType(name, field.getGenericType());
}

From source file:com.mstiles92.plugins.stileslib.config.ConfigObject.java

@SuppressWarnings("rawtypes")
protected Object loadObject(Field field, ConfigurationSection cs, String path, int depth) throws Exception {
    Class clazz = getClassAtDepth(field.getGenericType(), depth);
    if (ConfigObject.class.isAssignableFrom(clazz) && isConfigurationSection(cs.get(path))) {
        return getConfigObject(clazz, cs.getConfigurationSection(path));
    } else if (Location.class.isAssignableFrom(clazz) && isJSON(cs.get(path))) {
        return getLocation((String) cs.get(path));
    } else if (Vector.class.isAssignableFrom(clazz) && isJSON(cs.get(path))) {
        return getVector((String) cs.get(path));
    } else if (Map.class.isAssignableFrom(clazz) && isConfigurationSection(cs.get(path))) {
        return getMap(field, cs.getConfigurationSection(path), path, depth);
    } else if (clazz.isEnum() && isString(cs.get(path))) {
        return getEnum(clazz, (String) cs.get(path));
    } else if (List.class.isAssignableFrom(clazz) && isConfigurationSection(cs.get(path))) {
        Class subClazz = getClassAtDepth(field.getGenericType(), depth + 1);
        if (ConfigObject.class.isAssignableFrom(subClazz) || Location.class.isAssignableFrom(subClazz)
                || Vector.class.isAssignableFrom(subClazz) || Map.class.isAssignableFrom(subClazz)
                || List.class.isAssignableFrom(subClazz) || subClazz.isEnum()) {
            return getList(field, cs.getConfigurationSection(path), path, depth);
        } else {// w  w w .  j a  v a 2s . co m
            return cs.get(path);
        }
    } else {
        return cs.get(path);
    }
}

From source file:org.eiichiro.bootleg.json.JSONRequest.java

@SuppressWarnings("unchecked")
private Object body(Type type, String name, final JsonElement element) {
    Function<String, Object> value = new Function<String, Object>() {

        public Object apply(String name) {
            if (element instanceof JsonObject) {
                JsonObject jsonObject = (JsonObject) element;
                return jsonObject.get(name);
            } else {
                return null;
            }/* w  w  w .ja  va  2s.c om*/
        }

    };
    Function<String, Collection<Object>> values = new Function<String, Collection<Object>>() {

        public Collection<Object> apply(String name) {
            if (element instanceof JsonObject) {
                JsonObject jsonObject = (JsonObject) element;
                JsonElement jsonElement = jsonObject.get(name);

                if (jsonElement != null && jsonElement.isJsonArray()) {
                    Collection<Object> collection = new ArrayList<Object>();
                    Iterator<JsonElement> iterator = jsonElement.getAsJsonArray().iterator();

                    while (iterator.hasNext()) {
                        collection.add(iterator.next());
                    }

                    return (collection.isEmpty()) ? null : collection;
                } else {
                    logger.warn("Element [" + name + "] is not a JSON array");
                    return null;
                }

            } else if ((name == null || name.isEmpty()) && element instanceof JsonArray) {
                JsonArray array = (JsonArray) element;
                Collection<Object> collection = new ArrayList<Object>();
                Iterator<JsonElement> iterator = array.iterator();

                while (iterator.hasNext()) {
                    collection.add(iterator.next());
                }

                return (collection.isEmpty()) ? null : collection;
            } else {
                return null;
            }
        }

    };

    if (name != null && !name.isEmpty()) {
        if (Types.isCollection(type)) {
            if (Types.isSupportedCollection(type)) {
                Class<?> elementType = Types.getElementType(type);

                if (!Types.isCoreValueType(elementType) && !Types.isUserDefinedValueType(elementType)) {
                    // Named collection of user-defined object type.
                    Collection<Object> jsonElements = values.apply(name);

                    if (jsonElements == null) {
                        logger.debug("Collection named [" + name + "] not found");
                        return jsonElements;
                    }

                    try {
                        Class<?> implementationType = Types.getDefaultImplementationType(type);
                        Collection<Object> collection = (Collection<Object>) implementationType.newInstance();

                        try {
                            for (Object jsonElement : jsonElements) {
                                Object instance = elementType.newInstance();

                                for (Field field : elementType.getDeclaredFields()) {
                                    Object object = body(field.getGenericType(), field.getName(),
                                            (JsonElement) jsonElement);

                                    if (object != null) {
                                        field.setAccessible(true);
                                        field.set(instance, object);
                                    }
                                }

                                collection.add(instance);
                            }

                            return (collection.isEmpty()) ? null : collection;
                        } catch (Exception e) {
                            logger.warn("Cannot instantiate [" + elementType + "] (Collection element type of ["
                                    + type + "])", e);
                        }

                    } catch (Exception e) {
                        logger.debug("Cannot instantiate [" + Types.getDefaultImplementationType(type)
                                + "] (Default implementation type of [" + type + "])", e);
                    }

                    return null;
                }
            }

        } else if (!Types.isCoreValueType(type) && !Types.isUserDefinedValueType(type)) {
            // Named user-defined object type.
            Class<?> rawType = Types.getRawType(type);
            Object jsonElement = value.apply(name);

            try {
                Object instance = rawType.newInstance();

                for (Field field : rawType.getDeclaredFields()) {
                    Object object = body(field.getGenericType(), field.getName(), (JsonElement) jsonElement);

                    if (object != null) {
                        field.setAccessible(true);
                        field.set(instance, object);
                    }
                }

                return instance;
            } catch (Exception e) {
                logger.warn("Cannot instantiate [" + type + "]", e);
            }

            return null;
        }

    } else {
        if (Types.isCollection(type)) {
            if (Types.isSupportedCollection(type)) {
                Collection<Object> objects = values.apply(name);

                if (objects == null) {
                    logger.debug("Posted JSON element is not a JSON array");
                    return objects;
                }

                try {
                    Class<?> implementationType = Types.getDefaultImplementationType(type);
                    Collection<Object> collection = (Collection<Object>) implementationType.newInstance();
                    Class<?> elementType = Types.getElementType(type);
                    boolean coreValueType = Types.isCoreValueType(elementType);

                    try {
                        if (coreValueType || Types.isUserDefinedValueType(elementType)) {
                            // No-named collection of core value type.
                            // No-named collection of user-defined value type.
                            for (Object object : objects) {
                                Object convert = (coreValueType) ? convert(object, elementType)
                                        : convertUserDefinedValueType(object, elementType);

                                if (convert != null && ClassUtils.primitiveToWrapper(elementType)
                                        .isAssignableFrom(convert.getClass())) {
                                    collection.add(convert);
                                } else {
                                    logger.debug("Parameter [" + convert + "] cannot be converted to ["
                                            + elementType + "]");
                                }
                            }

                        } else {
                            // No-named collection of user-defined object type.
                            for (Object jsonElement : objects) {
                                Object instance = elementType.newInstance();

                                for (Field field : elementType.getDeclaredFields()) {
                                    Object object = body(field.getGenericType(), field.getName(),
                                            (JsonElement) jsonElement);

                                    if (object != null) {
                                        field.setAccessible(true);
                                        field.set(instance, object);
                                    }
                                }

                                collection.add(instance);
                            }
                        }

                        return (collection.isEmpty()) ? null : collection;
                    } catch (Exception e) {
                        logger.warn("Cannot instantiate [" + elementType + "] (Collection element type of ["
                                + type + "])", e);
                    }

                } catch (Exception e) {
                    logger.debug("Cannot instantiate [" + Types.getDefaultImplementationType(type)
                            + "] (Default implementation type of [" + type + "])", e);
                }
            }

            return null;
        }
    }

    return parameter(type, name, value, values);
}

From source file:com.mstiles92.plugins.stileslib.config.ConfigObject.java

@SuppressWarnings("rawtypes")
protected Object saveObject(Object obj, Field field, ConfigurationSection cs, String path, int depth)
        throws Exception {
    Class clazz = getClassAtDepth(field.getGenericType(), depth);
    if (ConfigObject.class.isAssignableFrom(clazz) && isConfigObject(obj)) {
        return getConfigObject((ConfigObject) obj, path, cs);
    } else if (Location.class.isAssignableFrom(clazz) && isLocation(obj)) {
        return getLocation((Location) obj);
    } else if (Vector.class.isAssignableFrom(clazz) && isVector(obj)) {
        return getVector((Vector) obj);
    } else if (Map.class.isAssignableFrom(clazz) && isMap(obj)) {
        return getMap((Map) obj, field, cs, path, depth);
    } else if (clazz.isEnum() && isEnum(clazz, obj)) {
        return getEnum((Enum) obj);
    } else if (List.class.isAssignableFrom(clazz) && isList(obj)) {
        Class subClazz = getClassAtDepth(field.getGenericType(), depth + 1);
        if (ConfigObject.class.isAssignableFrom(subClazz) || Location.class.isAssignableFrom(subClazz)
                || Vector.class.isAssignableFrom(subClazz) || Map.class.isAssignableFrom(subClazz)
                || List.class.isAssignableFrom(subClazz) || subClazz.isEnum()) {
            return getList((List) obj, field, cs, path, depth);
        } else {//from w  ww  .j a  va2s .c  o m
            return obj;
        }
    } else {
        return obj;
    }
}

From source file:info.archinnov.achilles.internal.metadata.parsing.PropertyParser.java

public <V> PropertyMeta parseListProperty(PropertyParsingContext context) {

    log.debug("Parsing property {} as list property of entity class {}", context.getCurrentPropertyName(),
            context.getCurrentEntityClass().getCanonicalName());

    Class<?> entityClass = context.getCurrentEntityClass();
    Field field = context.getCurrentField();
    boolean timeUUID = isTimeUUID(context, field);
    Class<V> valueClass;/* ww w  .  j  a va2s  .com*/
    Type genericType = field.getGenericType();
    valueClass = inferValueClassForListOrSet(genericType, entityClass);

    Method[] accessors = entityIntrospector.findAccessors(entityClass, field);
    PropertyType type = LIST;

    PropertyMeta listMeta = factory().objectMapper(context.getCurrentObjectMapper()).type(type)
            .propertyName(context.getCurrentPropertyName())
            .entityClassName(context.getCurrentEntityClass().getCanonicalName())
            .consistencyLevels(context.getCurrentConsistencyLevels()).accessors(accessors).field(field)
            .timeuuid(timeUUID).build(Void.class, valueClass);

    log.trace("Built list property meta for property {} of entity class {} : {}", listMeta.getPropertyName(),
            context.getCurrentEntityClass().getCanonicalName(), listMeta);

    return listMeta;

}

From source file:info.archinnov.achilles.internal.metadata.parsing.PropertyParser.java

public <V> PropertyMeta parseSetProperty(PropertyParsingContext context) {
    log.debug("Parsing property {} as set property of entity class {}", context.getCurrentPropertyName(),
            context.getCurrentEntityClass().getCanonicalName());

    Class<?> entityClass = context.getCurrentEntityClass();
    Field field = context.getCurrentField();
    boolean timeUUID = isTimeUUID(context, field);

    Class<V> valueClass;// w  w  w.  ja  v a 2  s.com
    Type genericType = field.getGenericType();

    valueClass = inferValueClassForListOrSet(genericType, entityClass);
    Method[] accessors = entityIntrospector.findAccessors(entityClass, field);
    PropertyType type = SET;

    PropertyMeta setMeta = factory().objectMapper(context.getCurrentObjectMapper()).type(type)
            .propertyName(context.getCurrentPropertyName())
            .entityClassName(context.getCurrentEntityClass().getCanonicalName())
            .consistencyLevels(context.getCurrentConsistencyLevels()).accessors(accessors).field(field)
            .timeuuid(timeUUID).build(Void.class, valueClass);

    log.trace("Built set property meta for property {} of  entity class {} : {}", setMeta.getPropertyName(),
            context.getCurrentEntityClass().getCanonicalName(), setMeta);

    return setMeta;
}