Example usage for java.lang.reflect ParameterizedType getActualTypeArguments

List of usage examples for java.lang.reflect ParameterizedType getActualTypeArguments

Introduction

In this page you can find the example usage for java.lang.reflect ParameterizedType getActualTypeArguments.

Prototype

Type[] getActualTypeArguments();

Source Link

Document

Returns an array of Type objects representing the actual type arguments to this type.

Usage

From source file:com.opensymphony.xwork2.conversion.impl.DefaultObjectTypeDeterminer.java

/**
 * Returns the class for the given field via generic type check.
 *
 * @param parentClass the Class which contains as a property the Map or Collection we are finding the key for.
 * @param property    the property of the Map or Collection for the given parent class
 * @param element     <tt>true</tt> for indexed types and Maps.
 * @return Class of the specified field.
 *//*from w w w.j a v a2s . c  o  m*/
private Class getClass(Class parentClass, String property, boolean element) {
    try {
        Field field = reflectionProvider.getField(parentClass, property);
        Type genericType = null;
        // Check fields first
        if (field != null) {
            genericType = field.getGenericType();
        }
        // Try to get ParameterType from setter method
        if (genericType == null || !(genericType instanceof ParameterizedType)) {
            try {
                Method setter = reflectionProvider.getSetMethod(parentClass, property);
                genericType = setter != null ? setter.getGenericParameterTypes()[0] : null;
            } catch (ReflectionException | IntrospectionException e) {
                // ignore
            }
        }

        // Try to get ReturnType from getter method
        if (genericType == null || !(genericType instanceof ParameterizedType)) {
            try {
                Method getter = reflectionProvider.getGetMethod(parentClass, property);
                genericType = getter.getGenericReturnType();
            } catch (ReflectionException | IntrospectionException e) {
                // ignore
            }
        }

        if (genericType instanceof ParameterizedType) {
            ParameterizedType type = (ParameterizedType) genericType;
            int index = (element && type.getRawType().toString().contains(Map.class.getName())) ? 1 : 0;
            Type resultType = type.getActualTypeArguments()[index];
            if (resultType instanceof ParameterizedType) {
                return (Class) ((ParameterizedType) resultType).getRawType();
            }
            return (Class) resultType;
        }
    } catch (Exception e) {
        LOG.debug("Error while retrieving generic property class for property: {}", property, e);
    }
    return null;
}

From source file:org.openmrs.module.sync.SyncUtil.java

/**
 * This monstrosity looks for getter(s) on the parent object of an OpenmrsObject that return a
 * collection of the originally passed in OpenmrsObject type. This then explicitly removes the
 * object from the parent collection, and if the parent is a Patient or Person, calls save on
 * the parent.//from  w w w .  ja v a 2 s.  c o  m
 * 
 * @param item -- the OpenmrsObject to remove and save
 */
private static void removeFromPatientParentCollectionAndSave(OpenmrsObject item) {
    Field[] f = item.getClass().getDeclaredFields();
    for (int k = 0; k < f.length; k++) {
        Type fieldType = f[k].getGenericType();
        if (org.openmrs.OpenmrsObject.class.isAssignableFrom((Class) fieldType)) { //if the property is an OpenmrsObject (excludes lists, etc..)
            Method getter = getGetterMethod(item.getClass(), f[k].getName()); //get the getters
            OpenmrsObject parent = null; //the parent object
            if (getter == null) {
                continue; //no prob -- eliminates most utility methods on item
            }
            try {
                parent = (OpenmrsObject) getter.invoke(item, null); //get the parent object
            } catch (Exception ex) {
                log.debug(
                        "in removeFromParentCollection:  getter probably did not return an object that could be case as an OpenmrsObject",
                        ex);
            }
            if (parent != null) {
                Method[] methods = getter.getReturnType().getDeclaredMethods(); //get the Parent's methods to inspect
                for (Method method : methods) {
                    Type type = method.getGenericReturnType();
                    //return is a parameterizable and there are 0 arguments to method and the return is a Collection
                    if (ParameterizedType.class.isAssignableFrom(type.getClass())
                            && method.getGenericParameterTypes().length == 0
                            && method.getName().contains("get")) { //get the methods on Person that return Lists or Sets
                        ParameterizedType pt = (ParameterizedType) type;
                        for (int i = 0; i < pt.getActualTypeArguments().length; i++) {
                            Type t = pt.getActualTypeArguments()[i];
                            // if the return type matches the original object, and the return is not a Map
                            if (item.getClass().equals(t)
                                    && !pt.getRawType().toString().equals(java.util.Map.class.toString())
                                    && java.util.Collection.class.isAssignableFrom((Class) pt.getRawType())) {
                                try {
                                    Object colObj = (Object) method.invoke(parent, null); //get the list
                                    if (colObj != null) {
                                        java.util.Collection collection = (java.util.Collection) colObj;
                                        Iterator it = collection.iterator();
                                        boolean atLeastOneRemoved = false;
                                        while (it.hasNext()) {
                                            OpenmrsObject omrsobj = (OpenmrsObject) it.next();
                                            if (omrsobj.getUuid() != null
                                                    && omrsobj.getUuid().equals(item.getUuid())) { //compare uuid of original item with Collection contents
                                                it.remove();
                                                atLeastOneRemoved = true;
                                            }
                                            if (atLeastOneRemoved && (parent instanceof org.openmrs.Patient
                                                    || parent instanceof org.openmrs.Person)) {
                                                // this is commented out because deleting of patients fails if it is here.
                                                // we really should not need to call "save", that can only cause problems.
                                                // removing the object from the parent collection is the important part, which we're doing above
                                                //Context.getService(SyncService.class).saveOrUpdate(parent);
                                            }
                                        }
                                    }
                                } catch (Exception ex) {
                                    log.error("Failed to build new collection", ex);
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}

From source file:com.google.code.pathlet.web.ognl.impl.InstantiatingNullHandler.java

/**
 * Returns the class for the given field via generic type check.
 *
 * @param parentClass the Class which contains as a property the Map or Collection we are finding the key for.
 * @param property    the property of the Map or Collection for the given parent class
 * @param element     <tt>true</tt> for indexed types and Maps.
 * @return Class of the specified field.
 */// w  ww.ja v a 2  s  .  c  o  m
private Class getClass(Class parentClass, String property, boolean element) {

    try {

        Field field = reflectionProvider.getField(parentClass, property);

        Type genericType = null;

        // Check fields first
        if (field != null) {
            genericType = field.getGenericType();
        }

        // Try to get ParameterType from setter method
        if (genericType == null || !(genericType instanceof ParameterizedType)) {
            try {
                Method setter = reflectionProvider.getSetMethod(parentClass, property);
                genericType = setter.getGenericParameterTypes()[0];
            } catch (ReflectionException ognle) {
                ; // ignore
            } catch (IntrospectionException ie) {
                ; // ignore
            }
        }

        // Try to get ReturnType from getter method
        if (genericType == null || !(genericType instanceof ParameterizedType)) {
            try {
                Method getter = reflectionProvider.getGetMethod(parentClass, property);
                genericType = getter.getGenericReturnType();
            } catch (ReflectionException ognle) {
                ; // ignore
            } catch (IntrospectionException ie) {
                ; // ignore
            }
        }

        if (genericType instanceof ParameterizedType) {

            ParameterizedType type = (ParameterizedType) genericType;

            int index = (element && type.getRawType().toString().contains(Map.class.getName())) ? 1 : 0;

            Type resultType = type.getActualTypeArguments()[index];

            if (resultType instanceof ParameterizedType) {
                return (Class) ((ParameterizedType) resultType).getRawType();
            }
            return (Class) resultType;

        }
    } catch (Exception e) {
        throw new ConvertException(e);
    }
    return null;
}

From source file:org.guicerecipes.spring.support.AutowiredMemberProvider.java

private Collection provideCollectionValues(Collection collection, Member member, TypeLiteral<?> type,
        Predicate<Binding> filter) {
    Type typeInstance = type.getType();
    if (typeInstance instanceof ParameterizedType) {
        ParameterizedType parameterizedType = (ParameterizedType) typeInstance;
        Type[] arguments = parameterizedType.getActualTypeArguments();
        if (arguments.length == 1) {
            Type argument = arguments[0];
            if (argument instanceof Class) {
                Class<?> componentType = (Class<?>) argument;
                if (componentType != Object.class) {
                    Set<Binding<?>> set = getSortedBindings(componentType, filter);
                    if (set.isEmpty()) {
                        // TODO return null or empty collection if nothing to inject?
                        return null;
                    }/* www  .jav a 2s .  co  m*/
                    for (Binding<?> binding : set) {
                        Object value = binding.getProvider().get();
                        collection.add(value);
                    }
                    return collection;
                }
            }
        }
    }
    // TODO return null or empty collection if nothing to inject?
    return null;
}

From source file:org.guicerecipes.spring.support.AutowiredMemberProvider.java

protected Map provideMapValues(Map map, Member member, TypeLiteral<?> type, Predicate<Binding> filter) {
    Type typeInstance = type.getType();
    if (typeInstance instanceof ParameterizedType) {
        ParameterizedType parameterizedType = (ParameterizedType) typeInstance;
        Type[] arguments = parameterizedType.getActualTypeArguments();
        if (arguments.length == 2) {
            Type key = arguments[0];
            if (key instanceof Class) {
                Class<?> keyType = (Class<?>) key;
                if ((keyType != Object.class) && (keyType != String.class)) {
                    throw new ProvisionException("Cannot inject Map instances with a key type of "
                            + keyType.getName() + " for " + member);
                }// w  ww  .j  av a 2  s  .  c o m
                Type valueType = arguments[1];
                if (valueType instanceof Class) {
                    Class<?> componentType = (Class<?>) valueType;
                    if (componentType != Object.class) {
                        Set<Binding<?>> set = getSortedBindings(componentType, filter);
                        if (set.isEmpty()) {
                            // TODO return null or empty collection if nothing to inject?
                            return null;
                        }
                        for (Binding<?> binding : set) {
                            Object keyValue = binding.getKey().toString();
                            Object value = binding.getProvider().get();
                            map.put(keyValue, value);
                        }
                        return map;
                    }
                }
            }
        }
    }
    // TODO return null or empty collection if nothing to inject?
    return null;
}

From source file:org.apache.axis2.jaxws.marshaller.impl.alt.DocLitWrappedMinimalMethodMarshaller.java

/**
 * Return ComponentType, might need to look at the GenericType
 * @param pd ParameterDesc or null if return
 * @param operationDesc OperationDescription
 * @param msrd MarshalServiceRuntimeDescription
 * @return//www .ja va2  s  . com
 */
private static Class getComponentType(ParameterDescription pd, OperationDescription operationDesc,
        MarshalServiceRuntimeDescription msrd) {
    Class componentType = null;
    if (log.isDebugEnabled()) {
        log.debug("start getComponentType");
        log.debug(" ParameterDescription=" + pd);
    }

    // Determine if array, list, or other
    Class cls = null;
    if (pd == null) {
        cls = operationDesc.getResultActualType();
    } else {
        cls = pd.getParameterActualType();
    }

    if (cls != null) {
        if (cls.isArray()) {
            componentType = cls.getComponentType();
        } else if (List.class.isAssignableFrom(cls)) {
            if (log.isDebugEnabled()) {
                log.debug("Parameter is a List: " + cls);
            }
            Method method = msrd.getMethod(operationDesc);
            if (log.isDebugEnabled()) {
                log.debug("Method is: " + method);
            }
            Type genericType = null;
            if (pd == null) {
                genericType = method.getGenericReturnType();
            } else {
                ParameterDescription[] pds = operationDesc.getParameterDescriptions();
                for (int i = 0; i < pds.length; i++) {
                    if (pds[i] == pd) {
                        genericType = method.getGenericParameterTypes()[i];
                    }
                }
            }
            if (log.isDebugEnabled()) {
                log.debug("genericType is: " + genericType.getClass() + " " + genericType);
            }
            if (genericType instanceof Class) {
                if (log.isDebugEnabled()) {
                    log.debug(" genericType instanceof Class");
                }
                componentType = String.class;
            } else if (genericType instanceof ParameterizedType) {
                if (log.isDebugEnabled()) {
                    log.debug(" genericType instanceof ParameterizedType");
                }
                ParameterizedType pt = (ParameterizedType) genericType;
                if (pt.getRawType() == Holder.class) {
                    if (log.isDebugEnabled()) {
                        log.debug(" strip off holder");
                    }
                    genericType = pt.getActualTypeArguments()[0];
                    if (genericType instanceof Class) {
                        componentType = String.class;
                    } else if (genericType instanceof ParameterizedType) {
                        pt = (ParameterizedType) genericType;
                    }
                }
                if (componentType == null) {
                    Type comp = pt.getActualTypeArguments()[0];
                    if (log.isDebugEnabled()) {
                        log.debug(" comp =" + comp.getClass() + " " + comp);
                    }
                    if (comp instanceof Class) {
                        componentType = (Class) comp;
                    } else if (comp instanceof ParameterizedType) {
                        componentType = (Class) ((ParameterizedType) comp).getRawType();
                    }
                }
            }

        }
    }

    if (log.isDebugEnabled()) {
        log.debug("end getComponentType=" + componentType);
    }
    return componentType;
}

From source file:ductive.console.commands.register.spring.ArgumentParserBeanPostProcessor.java

@Override
public Object postProcessAfterInitialization(final Object bean, String beanName) throws BeansException {
    ReflectionUtils.doWithMethods(bean.getClass(), new MethodCallback() {
        @Override//from w  w w .  j av a2  s. c om
        public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException {
            ArgParser argParser = AnnotationUtils.findAnnotation(method, ArgParser.class);
            if (argParser == null)
                return;

            String qualifier = StringUtils.defaultIfEmpty(argParser.value(), null);

            if (!void.class.equals(argParser.bind())) {
                argParserRegistry.register(argParser.bind(), qualifier, bean, method);
                return;
            }

            Type genericReturnType = method.getGenericReturnType();
            Validate.isTrue(ParameterizedType.class.isInstance(genericReturnType),
                    String.format(
                            "method %s: return type of parser generator method must be a subclass of %s<?>",
                            method, Parser.class.getCanonicalName()));

            ParameterizedType pt = ParameterizedType.class.cast(genericReturnType);
            Validate.isTrue(Parser.class.isAssignableFrom((Class<?>) pt.getRawType()),
                    String.format(
                            "method %s: return type of parser generator method must be a subclass of %s<?>",
                            method, Parser.class.getCanonicalName()));

            Type[] genericParams = pt.getActualTypeArguments();
            Validate.isTrue(genericParams.length == 1);

            argParserRegistry.register((Class<?>) genericParams[0], qualifier, bean, method);
        }

    });
    return bean;
}

From source file:com.xiovr.unibot.bot.impl.BotGameConfigImpl.java

@Override
// public void loadSettings(Settings instance, Class<?> clazz, String fn)
public void loadSettings(Settings instance, String fn) {

    Class<?> clazz = instance.getClass().getInterfaces()[0];
    //      File file = new File("/" + DIR_PATH + "/" + fn);
    File file = new File(fn);
    Properties props = null;//from  w  w  w.  j a  va  2 s .  c  o  m
    try {
        props = BotUtils.loadProperties(file);

        // botEnvironment.setClientIp((props.getProperty("client.ip",
        // "127.0.0.1"));
    } catch (IOException e) {
        // e.printStackTrace();
        //         logger.warn("Can't load settings /" + DIR_PATH + "/" + fn
        //               + ". Create new settings file.");
        logger.warn("Can't load settings " + fn + ". Create new settings file.");
        props = createSettings(clazz, fn, "Bot v" + VERSION);

    }
    Method[] methods = clazz.getMethods();
    for (Method method : methods) {
        // Find setters
        if (method.getName().startsWith("set")) {

            if (method.isAnnotationPresent(Param.class)) {

                Annotation annotation = method.getAnnotation(Param.class);
                Param param = (Param) annotation;
                if (param.name().equals("") || param.values().length == 0) {
                    throw new RuntimeException("Wrong param in class " + clazz.getCanonicalName()
                            + " with method " + method.getName());
                }
                Class<?>[] paramClazzes = method.getParameterTypes();
                if (paramClazzes.length != 1) {
                    throw new RuntimeException("Error contract design in class " + clazz.getCanonicalName()
                            + " with method " + method.getName());
                }
                // Check param belongs to List
                Class<?> paramClazz = paramClazzes[0];

                try {
                    if (List.class.isAssignableFrom(paramClazz)) {
                        // Oh, its array...
                        // May be its InetSocketAddress?

                        Type[] gpt = method.getGenericParameterTypes();
                        if (gpt[0] instanceof ParameterizedType) {
                            ParameterizedType type = (ParameterizedType) gpt[0];
                            Type[] typeArguments = type.getActualTypeArguments();

                            for (Type typeArgument : typeArguments) {
                                Class<?> classType = ((Class<?>) typeArgument);
                                if (InetSocketAddress.class.isAssignableFrom(classType)) {
                                    List<InetSocketAddress> isaArr = new ArrayList<>();
                                    int cnt = Integer.parseInt(props.getProperty(param.name() + ".count", "2"));
                                    for (int i = 0; i < cnt; ++i) {
                                        String defaultHostname = "";
                                        String defaultPort = "";
                                        if (param.values().length > i * 2) {
                                            defaultHostname = param.values()[i * 2];
                                            defaultPort = param.values()[i * 2 + 1];
                                        } else {
                                            defaultHostname = DEFAULT_HOSTNAME;
                                            defaultPort = String.valueOf(DEFAULT_PORT);
                                        }
                                        InetSocketAddress isa = new InetSocketAddress(
                                                props.getProperty(
                                                        param.name() + "." + String.valueOf(i) + ".ip",
                                                        defaultHostname),
                                                Integer.parseInt(props.getProperty(
                                                        param.name() + "." + String.valueOf(i) + ".port",
                                                        defaultPort)));
                                        // invocableClazz.getMethod(method.getName(),
                                        // InetSocketAddress.class).invoke(
                                        // instance, isa);
                                        isaArr.add(isa);

                                    }

                                    method.invoke(instance, isaArr);

                                } else {
                                    throw new RuntimeException("Settings param in class "
                                            + clazz.getCanonicalName() + " with method " + method.getName()
                                            + " not implemented yet");
                                }
                            }

                        }
                    } else if (paramClazz.isPrimitive()) {
                        if (int.class.isAssignableFrom(paramClazz)) {
                            method.invoke(instance,
                                    Integer.parseInt(props.getProperty(param.name(), param.values()[0])));
                        } else if (long.class.isAssignableFrom(paramClazz)) {
                            method.invoke(instance,
                                    Long.parseLong(props.getProperty(param.name(), param.values()[0])));
                        } else if (boolean.class.isAssignableFrom(paramClazz)) {
                            method.invoke(instance,
                                    Boolean.parseBoolean(props.getProperty(param.name(), param.values()[0])));
                        } else if (double.class.isAssignableFrom(paramClazz)) {
                            method.invoke(instance,
                                    Double.parseDouble(props.getProperty(param.name(), param.values()[0])));
                        }

                    } else if (String.class.isAssignableFrom(paramClazz)) {
                        method.invoke(instance, props.getProperty(param.name(), param.values()[0]));
                    } else {
                        throw new RuntimeException("Settings param in class " + clazz.getCanonicalName()
                                + " with method " + method.getName() + " not implemented yet");
                    }
                } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }
}

From source file:com.mercatis.lighthouse3.persistence.commons.rest.DomainModelEntityDAOImplementation.java

/**
 * Generic constructor, necessary for setting the <CODE>entityType</CODE>
 * property at runtime.//from  w ww .j  av a2s  .  c om
 */
@SuppressWarnings("rawtypes")
public DomainModelEntityDAOImplementation() {
    try {
        ParameterizedType genericSuperclass = (ParameterizedType) getClass().getGenericSuperclass();
        Type[] actualTypeArguments = genericSuperclass.getActualTypeArguments();
        this.entityType = (Class) actualTypeArguments[0];
    } catch (Throwable t) {
        this.entityType = DomainModelEntity.class;
    }
}

From source file:org.debux.webmotion.server.handler.ExecutorParametersConvertorHandler.java

protected Object convert(List<ParameterTree> parameterTrees, Class<?> type, Type genericType) throws Exception {
    Object result = null;/*from  w w  w. j av  a 2  s  . c o  m*/

    if (type.isArray()) {
        Class<?> componentType = type.getComponentType();

        Object[] tabConverted = (Object[]) Array.newInstance(componentType, parameterTrees.size());

        int index = 0;
        for (ParameterTree parameterTree : parameterTrees) {
            Object objectConverted = convert(parameterTree, componentType, null);
            tabConverted[index] = objectConverted;
            index++;
        }

        result = tabConverted;

    } else if (Collection.class.isAssignableFrom(type)) {

        Collection instance;
        if (type.isInterface()) {
            if (List.class.isAssignableFrom(type)) {
                instance = new ArrayList();

            } else if (Set.class.isAssignableFrom(type)) {
                instance = new HashSet();

            } else if (SortedSet.class.isAssignableFrom(type)) {
                instance = new TreeSet();

            } else {
                instance = new ArrayList();
            }
        } else {
            instance = (Collection) type.newInstance();
        }

        Class convertType = String.class;
        if (genericType != null && genericType instanceof ParameterizedType) {
            ParameterizedType parameterizedType = (ParameterizedType) genericType;
            convertType = (Class) parameterizedType.getActualTypeArguments()[0];
        }

        for (ParameterTree parameterTree : parameterTrees) {
            Object converted = convert(parameterTree, convertType, null);
            instance.add(converted);
        }

        result = instance;
    }

    return result;
}