Example usage for java.lang.reflect Method getGenericParameterTypes

List of usage examples for java.lang.reflect Method getGenericParameterTypes

Introduction

In this page you can find the example usage for java.lang.reflect Method getGenericParameterTypes.

Prototype

@Override
public Type[] getGenericParameterTypes() 

Source Link

Usage

From source file:com.googlecode.jsonrpc4j.JsonRpcServer.java

/**
 * Invokes the given method on the {@code handler} passing
 * the given params (after converting them to beans\objects)
 * to it.//w  w w.  j  a v a 2  s  . com
 *
 * @param an optional service name used to locate the target object
 *  to invoke the Method on
 * @param m the method to invoke
 * @param params the params to pass to the method
 * @return the return value (or null if no return)
 * @throws IOException on error
 * @throws IllegalAccessException on error
 * @throws InvocationTargetException on error
 */
protected JsonNode invoke(Object target, Method m, List<JsonNode> params)
        throws IOException, IllegalAccessException, InvocationTargetException {

    // debug log
    if (LOGGER.isLoggable(Level.FINE)) {
        LOGGER.log(Level.FINE, "Invoking method: " + m.getName());
    }

    // convert the parameters
    Object[] convertedParams = new Object[params.size()];
    Type[] parameterTypes = m.getGenericParameterTypes();

    for (int i = 0; i < parameterTypes.length; i++) {
        JsonParser paramJsonParser = mapper.treeAsTokens(params.get(i));
        JavaType paramJavaType = TypeFactory.defaultInstance().constructType(parameterTypes[i]);
        convertedParams[i] = mapper.readValue(paramJsonParser, paramJavaType);
    }

    // invoke the method
    Object result = m.invoke(target, convertedParams);
    return (m.getGenericReturnType() != null) ? mapper.valueToTree(result) : null;
}

From source file:org.restlet.ext.jaxrs.internal.wrappers.params.ParameterList.java

/**
 * @param executeMethod// ww  w .j  a  v a  2s.com
 * @param annotatedMethod
 * @param tlContext
 * @param leaveEncoded
 * @param jaxRsProviders
 * @param extensionBackwardMapping
 * @param entityAllowed
 * @param logger
 * @throws MissingAnnotationException
 * @throws IllegalTypeException
 *             if one of the parameters contains a &#64;{@link Context} on
 *             an type that must not be annotated with &#64;{@link Context}.
 * @throws IllegalPathParamTypeException
 */
public ParameterList(Method executeMethod, Method annotatedMethod, ThreadLocalizedContext tlContext,
        boolean leaveEncoded, JaxRsProviders jaxRsProviders, ExtensionBackwardMapping extensionBackwardMapping,
        boolean entityAllowed, Logger logger)
        throws MissingAnnotationException, IllegalTypeException, IllegalPathParamTypeException {
    this(executeMethod.getParameterTypes(), executeMethod.getGenericParameterTypes(),
            annotatedMethod.getParameterAnnotations(), tlContext, leaveEncoded, jaxRsProviders,
            extensionBackwardMapping, true, entityAllowed, logger, true);
}

From source file:org.nextframework.controller.MultiActionController.java

protected Class<?> getCommandClass(Method method, int commandIndex) {
    //TODO TENTAR DESCOBRIR O COMMAND MESMO QUANDO UTILIZAR GENERICS
    Class<?> commandClass = null;
    Method metodoOriginal = method;
    do {/*from w w  w  .j a v  a  2 s.  c o  m*/
        Type[] genericParameterTypes = method.getGenericParameterTypes();
        Type type = genericParameterTypes[commandIndex];
        if (type instanceof TypeVariable<?>) {
            TypeVariable<?> typeVariable = (TypeVariable<?>) type;
            String typeVariableName = typeVariable.getName();

            TypeVariable<?>[] typeParameters = this.getClass().getTypeParameters();
            if (typeParameters.length != 0) {
                throw new NextException("Implementar achar tipo de command por genericTypeParameters");
            }
            Type genericSuperclass = this.getClass().getGenericSuperclass();
            if (genericSuperclass instanceof ParameterizedType) {
                TypeVariable<?>[] typeParametersMethodClass = method.getDeclaringClass().getTypeParameters();
                int i = 0;
                for (TypeVariable<?> variable : typeParametersMethodClass) {
                    if (variable.getName().equals(typeVariableName)) {
                        commandClass = (Class<?>) ((ParameterizedType) genericSuperclass)
                                .getActualTypeArguments()[i];
                    }
                    i++;
                }
            }
            break;
        }
        if (type instanceof Object) {
            method = getSuperClassMethod(method);
        }
    } while (commandClass == null && method != null);
    if (commandClass == null) {
        commandClass = metodoOriginal.getParameterTypes()[metodoOriginal.getParameterTypes().length - 1];
    }
    //      if(commandClass.equals(Object.class)){
    //         logger.warn("Utilizando classe java.lang.Object como command");
    //      }
    return commandClass;
}

From source file:org.topazproject.otm.metadata.AnnotationClassMetaFactory.java

private void registerSubClassResolver(ClassDefinition def, final Method method) throws OtmException {
    if (!Modifier.isStatic(method.getModifiers()) || !Modifier.isPublic(method.getModifiers()))
        throw new OtmException("@SubClassResolver method '" + method + "' is not public and static");

    Method resolve = org.topazproject.otm.SubClassResolver.class.getDeclaredMethods()[0];
    assert resolve.getName().equals("resolve") : "unexpected method found in SubClassResolver: " + resolve;

    if (method.getGenericReturnType() != resolve.getGenericReturnType())
        throw new OtmException(
                "@SubClassResolver method '" + method + "' does not return " + resolve.getGenericReturnType());

    if (!Arrays.equals(method.getGenericParameterTypes(), resolve.getGenericParameterTypes()))
        throw new OtmException("@SubClassResolver method '" + method + "' has wrong signature - " + "required: "
                + Arrays.toString(resolve.getGenericParameterTypes()));

    sf.addSubClassResolver(def.getName(), new org.topazproject.otm.SubClassResolver() {
        public ClassMetadata resolve(ClassMetadata superEntity, EntityMode instantiatableIn, SessionFactory sf,
                Collection<String> typeUris, TripleStore.Result statements) {
            try {
                return (ClassMetadata) method.invoke(null, superEntity, instantiatableIn, sf, typeUris,
                        statements);//from   w  ww  .  j  ava  2  s . c  o  m
            } catch (Exception e) {
                if (e instanceof InvocationTargetException) {
                    Throwable t = ((InvocationTargetException) e).getCause();
                    if (t instanceof RuntimeException)
                        throw (RuntimeException) t;
                    if (t instanceof Error)
                        throw (Error) t;
                }

                throw new OtmException("Error invoking '" + method + "'", e);
            }
        }
    });
}

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

@SuppressWarnings("unchecked")
@Override//from w  ww.j  a v  a2 s  . co 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:com.xiovr.unibot.bot.impl.BotGameConfigImpl.java

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

    Properties props = new SortedProperties();
    try {//from   ww  w  .  j  av a2 s. c o  m
        //         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

@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;/*ww w .  ja  va  2  s .  co  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.xwtec.xwserver.util.json.JSONArray.java

/**
 * Get the collection type from a getter or setter, or null if no type was
 * found.<br/>/*from  ww w . ja  v a2s. c o m*/
 * Contributed by [Matt Small @ WaveMaker].
 */
public static Class[] getCollectionType(PropertyDescriptor pd, boolean useGetter) throws JSONException {

    Type type;
    if (useGetter) {
        Method m = pd.getReadMethod();
        type = m.getGenericReturnType();
    } else {
        Method m = pd.getWriteMethod();
        Type[] gpts = m.getGenericParameterTypes();

        if (1 != gpts.length) {
            throw new JSONException("method " + m + " is not a standard setter");
        }
        type = gpts[0];
    }

    if (!(type instanceof ParameterizedType)) {
        return null;
        // throw new JSONException("type not instanceof ParameterizedType:
        // "+type.getClass());
    }

    ParameterizedType pType = (ParameterizedType) type;
    Type[] actualTypes = pType.getActualTypeArguments();

    Class[] ret = new Class[actualTypes.length];
    for (int i = 0; i < ret.length; i++) {
        ret[i] = (Class) actualTypes[i];
    }

    return ret;
}

From source file:cn.webwheel.ActionSetter.java

private List<SetterInfo> parseArgs(Method method) throws IOException {
    Annotation[][] as = method.getParameterAnnotations();
    if (as.length == 0) {
        return Collections.emptyList();
    }/*  w w w . j  a  v a 2s .  co  m*/
    String[] names = MethodParameterNames.lookup(method);
    if (names == null || names.length != as.length) {
        names = new String[as.length];
    }
    for (int i = 0; i < names.length; i++) {
        for (int j = 0; j < as[i].length; j++) {
            if (as[i][j] instanceof WebParam) {
                String v = ((WebParam) as[i][j]).value();
                if (!v.isEmpty()) {
                    names[i] = v;
                    break;
                }
            }
        }
        if (names[i] == null) {
            logger.severe("need WebParam at argument[" + i + "] in " + method);
            names[i] = "arg" + i;
        }
        if (method.getParameterTypes()[i].isArray()) {
            if (names[i] != null)
                names[i] += "[]";
        }
    }
    List<SetterInfo> list = new ArrayList<SetterInfo>();
    for (int i = 0; i < names.length; i++) {
        SetterInfo si = new SetterInfo();
        list.add(si);
        si.paramName = names[i];
        JsonProperty jsp = null;
        for (Annotation a : as[i]) {
            if (a instanceof JsonProperty) {
                jsp = (JsonProperty) a;
                break;
            }
        }
        if (jsp != null) {
            si.setter = new JSonSetter(method.getGenericParameterTypes()[i]);
            continue;
        }
        si.setter = typeSetterMap.get(method.getGenericParameterTypes()[i]);
        if (si.setter != null) {
            continue;
        }
        si.setter = BeanSetter.create(method.getParameterTypes()[i], this);
        if (si.setter != null) {
            continue;
        }
        logger.severe("can not find setter at argument[" + i + "] in " + method);
        si.setter = new DefaultValueSetter(method.getParameterTypes()[i]);
    }
    return list;
}