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.mollie.api.resource.BaseResource.java

@SuppressWarnings("unchecked")
protected Class<T> returnedClass() {
    ParameterizedType parameterizedType = (ParameterizedType) getClass().getGenericSuperclass();
    return (Class<T>) parameterizedType.getActualTypeArguments()[0];
}

From source file:org.evosuite.utils.generic.GenericTypeInference.java

private void addToMap(ParameterizedType type, Type actualType, Map<TypeVariable<?>, Type> typeMap) {
    Type[] parameterTypes = type.getActualTypeArguments();
    TypeVariable<?>[] variables = ((Class<?>) type.getRawType()).getTypeParameters();
    for (int i = 0; i < parameterTypes.length; i++) {
        typeMap.put(variables[i], parameterTypes[i]);
    }//ww w .  ja  va 2  s  . c  o m
}

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

private Properties createSettings(Class<?> clazz, String fn, String comment) {

    Properties props = new SortedProperties();
    try {/* w  w w. j  a v a2  s.c om*/
        //         File file = new File("/" + DIR_PATH + "/" + fn);
        File file = new File(fn);
        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];
                    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)) {
                                    String[] vals = param.values();
                                    for (int i = 0; i < vals.length / 2; ++i) {
                                        props.setProperty(param.name() + "." + String.valueOf(i) + ".ip",
                                                vals[i * 2]);
                                        props.setProperty(param.name() + "." + String.valueOf(i) + ".port",
                                                vals[i * 2 + 1]);
                                    }
                                    props.setProperty(param.name() + ".count", String.valueOf(vals.length / 2));

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

                        }
                    } else if (paramClazz.isPrimitive()) {
                        props.setProperty(param.name(), param.values()[0]);

                    } else if (String.class.isAssignableFrom(paramClazz)) {

                        props.setProperty(param.name(), param.values()[0]);

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

                }
            }
        }

        BotUtils.saveProperties(file, props, comment);
    } catch (IOException e) {
        logger.error("Error save file " + fn);
    }
    return props;
}

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

@SuppressWarnings("unchecked")
@Override//from  www.  jav  a2 s. c  o m
public void saveSettings(Settings instance, String fn, String comment) {
    Class<?> clazz = instance.getClass().getInterfaces()[0];
    Class<?> invocableClazz = instance.getClass();
    //      File file = new File("/" + DIR_PATH + "/" + fn);
    File file = new File(fn);
    Properties props = new SortedProperties();

    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 = (List<InetSocketAddress>) invocableClazz
                                            .getMethod("get" + method.getName().substring(3)).invoke(instance);
                                    int cnt = isaArr.size();
                                    props.setProperty(param.name() + ".count", String.valueOf(cnt));
                                    for (int i = 0; i < cnt; ++i) {
                                        props.setProperty(param.name() + "." + String.valueOf(i) + ".ip",
                                                isaArr.get(i).getHostString());
                                        props.setProperty(param.name() + "." + String.valueOf(i) + ".port",
                                                String.valueOf(isaArr.get(i).getPort()));
                                    }
                                } else {
                                    throw new RuntimeException("Settings param in class "
                                            + clazz.getCanonicalName() + " with method " + method.getName()
                                            + " not implemented yet");
                                }
                            }

                        }
                    } else if (paramClazz.isPrimitive()) {
                        props.setProperty(param.name(), String.valueOf(invocableClazz
                                .getMethod("get" + method.getName().substring(3)).invoke(instance)));
                    } else if (String.class.isAssignableFrom(paramClazz)) {
                        props.setProperty(param.name(), (String) (invocableClazz
                                .getMethod("get" + method.getName().substring(3)).invoke(instance)));
                    } else {
                        throw new RuntimeException("Settings param in class " + clazz.getCanonicalName()
                                + " with method " + method.getName() + " not implemented yet");
                    }
                    BotUtils.saveProperties(file, props, "Bot v" + VERSION);
                } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException
                        | NoSuchMethodException | IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

From source file:cn.chenlichao.web.ssm.service.impl.BaseServiceImpl.java

@SuppressWarnings("unchecked")
public BaseServiceImpl() {
    //  Class  (, ?, void)  Type
    Type genType = getClass().getGenericSuperclass();

    // ??, , ?//from  ww  w.  j a  v a 2  s.  c om
    while (!genType.equals(Object.class)) {
        if (genType instanceof ParameterizedType) {
            ParameterizedType superType = (ParameterizedType) genType;
            Type[] params = superType.getActualTypeArguments();
            if (params.length == 2 && params[0] instanceof Class) {
                entityClass = (Class<E>) params[0];
                pkClass = (Class<PK>) params[1];
                break;
            }
        }
        if (genType instanceof Class) {
            genType = ((Class) genType).getGenericSuperclass();
        } else {
            break;
        }
    }
    LOGGER.debug("Entity Class: {}, PK class: {}", entityClass.getSimpleName(), pkClass.getSimpleName());
}

From source file:com.sdm.core.resource.RestResource.java

protected Class<T> getEntityClass() {
    ParameterizedType type = (ParameterizedType) this.getClass().getGenericSuperclass();
    Class<T> entityClass = (Class<T>) type.getActualTypeArguments()[0];
    return entityClass;
}

From source file:org.phenotips.data.internal.controller.AbstractComplexController.java

/**
 * In case all fields are code fields, then the controller can store data in memory as vocabulary objects rather
 * than strings.//from   w w w .j  av a2s  .  c  om
 *
 * @return true if all fields contain HPO codes
 */
protected boolean isCodeFieldsOnly() {
    Type type = this.getClass().getGenericSuperclass();
    if (!(type instanceof ParameterizedType)) {
        return false;
    }
    ParameterizedType t = (ParameterizedType) type;
    return new DefaultParameterizedType(null, List.class, VocabularyProperty.class)
            .equals(t.getActualTypeArguments()[0]);
}

From source file:org.raml.emitter.RamlEmitter.java

private void generateSequenceOfMaps(StringBuilder dump, int depth, List seq, ParameterizedType itemType) {
    Type rawType = itemType.getRawType();
    if (rawType instanceof Class && Map.class.isAssignableFrom((Class<?>) rawType)) {
        Type valueType = itemType.getActualTypeArguments()[1];
        if (valueType instanceof Class) {
            dump.append("\n");
            for (Object item : seq) {
                dump.append(indent(depth)).append(YAML_SEQ).append("\n");
                dumpMap(dump, depth + 1, valueType, (Map) item);
            }/* www  . j a  va  2 s. c  o m*/
        }
    }
}

From source file:org.jsonschema2pojo.integration.AdditionalPropertiesIT.java

@Test
public void additionalPropertiesOfStringArrayTypeOnly()
        throws SecurityException, NoSuchMethodException, ClassNotFoundException {

    ClassLoader resultsClassLoader = schemaRule.generateAndCompile(
            "/schema/additionalProperties/additionalPropertiesArraysOfStrings.json", "com.example",
            config("generateBuilders", true));

    Class<?> classWithNoAdditionalProperties = resultsClassLoader
            .loadClass("com.example.AdditionalPropertiesArraysOfStrings");
    Method getter = classWithNoAdditionalProperties.getMethod("getAdditionalProperties");

    ParameterizedType listType = (ParameterizedType) ((ParameterizedType) getter.getGenericReturnType())
            .getActualTypeArguments()[1];
    assertThat(listType.getActualTypeArguments()[0], is(equalTo((Type) String.class)));

    // setter with these types should exist:
    classWithNoAdditionalProperties.getMethod("setAdditionalProperty", String.class, List.class);

    // builder with these types should exist:
    Method builderMethod = classWithNoAdditionalProperties.getMethod("withAdditionalProperty", String.class,
            List.class);
    assertThat("the builder method returns this type", builderMethod.getReturnType(),
            typeEqualTo(classWithNoAdditionalProperties));

}

From source file:io.sinistral.proteus.server.tools.swagger.Reader.java

private static Class<?> getClassArgument(Type cls) {
    if (cls instanceof ParameterizedType) {
        final ParameterizedType parameterized = (ParameterizedType) cls;
        final Type[] args = parameterized.getActualTypeArguments();
        if (args.length != 1) {
            LOGGER.error("Unexpected class definition: {}", cls);
            return null;
        }/*from ww w. j av a 2s  . co m*/
        final Type first = args[0];
        if (first instanceof Class) {
            return (Class<?>) first;
        } else {
            return null;
        }
    } else {
        LOGGER.error("Unknown class definition: {}", cls);
        return null;
    }
}