Java Code Examples for java.lang.reflect.Method.getGenericParameterTypes()

The following are Jave code examples for showing how to use getGenericParameterTypes() of the java.lang.reflect.Method class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: flux-capacitor-client   File: UpcastInspector.java   View Source Code Vote up 6 votes
private static <T> Function<Data<T>, Object> invokeFunction(Method method, Object target, Class<T> dataType) {
    Type[] parameters = method.getGenericParameterTypes();
    if (parameters.length != 1) {
        throw new IllegalArgumentException(
                String.format("Upcaster method '%s' has unexpected number of parameters. Expected 1 or 0.", method));
    }
    if (parameters[0] instanceof ParameterizedType) {
        ParameterizedType parameterizedType = (ParameterizedType) parameters[0];
        if (parameterizedType.getRawType().equals(Data.class) && dataType
                .isAssignableFrom((Class<?>) parameterizedType.getActualTypeArguments()[0])) {
            return data -> invokeMethod(method, data, target);
        }
        if (dataType.isAssignableFrom((Class<?>) parameterizedType.getRawType())) {
            return data -> invokeMethod(method, data.getValue(), target);
        }
    } else if (dataType.isAssignableFrom((Class<?>) parameters[0])) {
        return data -> invokeMethod(method, data.getValue(), target);
    }
    throw new IllegalArgumentException(String.format(
            "First parameter in upcaster method '%s' is of unexpected type. Expected Data<%s> or %s.",
            method, dataType.getName(), dataType.getName()));
}
 
Example 2
Project: netto_rpc   File: ArgsDeserializer.java   View Source Code Vote up 6 votes
public boolean registerMethodParameterTypes(String service, Class<?> clazz) {

		Method[] methods = clazz.getMethods();

		for (Method method : methods) {
			Class<?> declaredClazz = method.getDeclaringClass();
			if (declaredClazz == Object.class) {
				continue;
			}

			Type[] parameterTypes = method.getGenericParameterTypes();
			String key = service + "/" + method.getName() + "/" + parameterTypes.length;
			this.serviceMethodParameterTypesCache.put(key, new ServiceMethodDesc(key, parameterTypes));

			String defaultKey = service + "/" + method.getName() + "/";
			this.serviceMethodParameterTypesCache.put(defaultKey, new ServiceMethodDesc(key, parameterTypes));
		}

		return false;

	}
 
Example 3
Project: Simplify-Core   File: AbstractJson.java   View Source Code Vote up 6 votes
/**
 * 查找泛型类型
 *
 * @param m
 * @return
 */
protected Type getActualTypeArguments(Method m) {
    Type[] genericParameterTypes = m.getGenericParameterTypes();
    for (Type type : genericParameterTypes) {
        Type[] actualTypeArguments = ReflectionUtils.getActualTypeArguments(type);
        if (null == actualTypeArguments || actualTypeArguments.length == 0)
            return null;
        //Map 取value的泛型
        if (actualTypeArguments.length > 1) {
            return actualTypeArguments[1];
            //Collection 取泛型
        } else {
            return actualTypeArguments[0];
        }
    }
    return null;
}
 
Example 4
Project: minijax   File: MinijaxApplication.java   View Source Code Vote up 6 votes
/**
 * Returns the param providers for a resource method.
 *
 * This is very similar to the logic used in building param providers for a normal
 * <code>@Inject</code> constructor, with one major difference.
 *
 * A resource method is allowed one special "entity" parameter representing the content body.
 * This entity parameter is handled by a <code>EntityProvider</code>.
 *
 * @param method The resource method.
 * @return The array of resource method param providers.
 */
private Provider<?>[] getParamProviders(final Method method) {
    final Class<?>[] paramClasses = method.getParameterTypes();
    final Type[] paramTypes = method.getGenericParameterTypes();
    final Annotation[][] annotations = method.getParameterAnnotations();
    final Provider<?>[] result = new Provider<?>[paramTypes.length];

    final Consumes consumes = method.getAnnotation(Consumes.class);
    final List<MediaType> consumesTypes = MediaTypeUtils.parseMediaTypes(consumes);
    boolean consumed = false;

    for (int i = 0; i < paramTypes.length; i++) {
        if (annotations[i].length == 0 && !consumed) {
            result[i] = new EntityProvider<>(paramClasses[i], paramTypes[i], annotations[i], consumesTypes);
            consumed = true;
        } else {
            result[i] = getInjector().getProvider(paramClasses[i], annotations[i]);
        }
    }
    return result;
}
 
Example 5
Project: incubator-servicecomb-java-chassis   File: TestJavassistUtils.java   View Source Code Vote up 6 votes
@Test
public void testInterface() throws Exception {
  ClassConfig classConfig = new ClassConfig();
  classConfig.setIntf(true);
  String intfName = "cse.ut.TestInterface";
  classConfig.setClassName(intfName);

  String source = "java.util.List method(java.util.Map map, java.util.Set set);";
  String genericSignature =
      "(Ljava/util/Map<Ljava/lang/String;Ljava/lang/String;>;Ljava/util/Set<Ljava/lang/String;>;)Ljava/util/List<Ljava/lang/String;>;";
  classConfig.addMethod(source, genericSignature);

  Class<?> intf = JavassistUtils.createClass(classConfig);

  Assert.assertEquals(intfName, intf.getName());
  Method method = ReflectUtils.findMethod(intf, "method");
  Assert.assertEquals("method", method.getName());
  Assert.assertEquals("java.util.List<java.lang.String>", method.getGenericReturnType().getTypeName());

  Type[] types = method.getGenericParameterTypes();
  Assert.assertEquals("java.util.Map<java.lang.String, java.lang.String>", types[0].getTypeName());
  Assert.assertEquals("java.util.Set<java.lang.String>", types[1].getTypeName());
}
 
Example 6
Project: framework   File: CommonUtils.java   View Source Code Vote up 6 votes
public static List<Class<?>> getMethodGenericParameterTypes(Method method) {
	List<Class<?>> results = new ArrayList<Class<?>>();
	Type[] genericParameterTypes = method.getGenericParameterTypes();
	for (Type genericParameterType : genericParameterTypes) {
		if (genericParameterType instanceof ParameterizedType) {
			ParameterizedType aType = (ParameterizedType) genericParameterType;
			Type[] parameterArgTypes = aType.getActualTypeArguments();
			for (Type parameterArgType : parameterArgTypes) {
				Class<?> parameterArgClass = (Class<?>) parameterArgType;
				results.add(parameterArgClass);
			}
			return results;
		}
	}
	return results;
}
 
Example 7
Project: OpenJSharp   File: Introspector.java   View Source Code Vote up 5 votes
private boolean isEventHandler(Method m) {
    // We assume that a method is an event handler if it has a single
    // argument, whose type inherit from java.util.Event.
    Type argTypes[] = m.getGenericParameterTypes();
    if (argTypes.length != 1) {
        return false;
    }
    return isSubclass(TypeResolver.erase(TypeResolver.resolveInClass(beanClass, argTypes[0])), EventObject.class);
}
 
Example 8
Project: openjdk-jdk10   File: ConvertingMethod.java   View Source Code Vote up 5 votes
private ConvertingMethod(Method m) throws OpenDataException {
    this.method = m;
    MXBeanMappingFactory mappingFactory = MXBeanMappingFactory.DEFAULT;
    returnMapping =
            mappingFactory.mappingForType(m.getGenericReturnType(), mappingFactory);
    Type[] params = m.getGenericParameterTypes();
    paramMappings = new MXBeanMapping[params.length];
    boolean identity = true;
    for (int i = 0; i < params.length; i++) {
        paramMappings[i] = mappingFactory.mappingForType(params[i], mappingFactory);
        identity &= DefaultMXBeanMappingFactory.isIdentity(paramMappings[i]);
    }
    paramConversionIsIdentity = identity;
}
 
Example 9
Project: Reer   File: RuleSourceBackedRuleAction.java   View Source Code Vote up 5 votes
public static <R, T> RuleSourceBackedRuleAction<R, T> create(ModelType<T> subjectType, R ruleSourceInstance) {
    ModelType<R> ruleSourceType = ModelType.typeOf(ruleSourceInstance);
    List<Method> mutateMethods = JavaReflectionUtil.findAllMethods(ruleSourceType.getConcreteClass(), new Spec<Method>() {
        public boolean isSatisfiedBy(Method element) {
            return element.isAnnotationPresent(Mutate.class);
        }
    });
    FormattingValidationProblemCollector problemsFormatter = new FormattingValidationProblemCollector("rule source", ruleSourceType);
    RuleSourceValidationProblemCollector problems = new DefaultRuleSourceValidationProblemCollector(problemsFormatter);

    if (mutateMethods.size() == 0) {
        problems.add("Must have at exactly one method annotated with @" + Mutate.class.getName());
    } else {
        if (mutateMethods.size() > 1) {
            problems.add("More than one method is annotated with @" + Mutate.class.getName());
        }

        for (Method ruleMethod : mutateMethods) {
            if (ruleMethod.getReturnType() != Void.TYPE) {
                problems.add(ruleMethod, "A rule method must return void");
            }
            Type[] parameterTypes = ruleMethod.getGenericParameterTypes();
            if (parameterTypes.length == 0 || !subjectType.isAssignableFrom(ModelType.of(parameterTypes[0]))) {
                problems.add(ruleMethod, String.format("First parameter of a rule method must be of type %s", subjectType));
            }
        }
    }

    if (problemsFormatter.hasProblems()) {
        throw new RuleActionValidationException(problemsFormatter.format());
    }

    return new RuleSourceBackedRuleAction<R, T>(ruleSourceInstance, new JavaMethod<R, T>(subjectType.getConcreteClass(), mutateMethods.get(0)));
}
 
Example 10
Project: GitHub   File: ServiceMethod.java   View Source Code Vote up 5 votes
Builder(Retrofit retrofit, Method method) {
  this.retrofit = retrofit;
  this.method = method;
  this.methodAnnotations = method.getAnnotations();
  this.parameterTypes = method.getGenericParameterTypes();
  this.parameterAnnotationsArray = method.getParameterAnnotations();
}
 
Example 11
Project: hadoop   File: TestPBImplRecords.java   View Source Code Vote up 5 votes
/**
 * this method generate record instance by calling newIntance
 * using reflection, add register the generated value to typeValueCache
 */
@SuppressWarnings("rawtypes")
private static Object generateByNewInstance(Class clazz) throws Exception {
  Object ret = typeValueCache.get(clazz);
  if (ret != null) {
    return ret;
  }
  Method newInstance = null;
  Type [] paramTypes = new Type[0];
  // get newInstance method with most parameters
  for (Method m : clazz.getMethods()) {
    int mod = m.getModifiers();
    if (m.getDeclaringClass().equals(clazz) &&
        Modifier.isPublic(mod) &&
        Modifier.isStatic(mod) &&
        m.getName().equals("newInstance")) {
      Type [] pts = m.getGenericParameterTypes();
      if (newInstance == null
          || (pts.length > paramTypes.length)) {
        newInstance = m;
        paramTypes = pts;
      }
    }
  }
  if (newInstance == null) {
    throw new IllegalArgumentException("type " + clazz.getName() +
        " does not have newInstance method");
  }
  Object [] args = new Object[paramTypes.length];
  for (int i=0;i<args.length;i++) {
    args[i] = genTypeValue(paramTypes[i]);
  }
  ret = newInstance.invoke(null, args);
  typeValueCache.put(clazz, ret);
  return ret;
}
 
Example 12
Project: ats-framework   File: ClassTemplateProcessor.java   View Source Code Vote up 5 votes
private String getReturnClassImports(
                                      Class<?> actionClass ) {

    Method[] actionClassMethods = actionClass.getDeclaredMethods();
    //using TreeSet to prevent duplication of imports and have sorted list
    Set<String> imports = new TreeSet<String>();
    for (Method m : actionClassMethods) {
        if (ActionClassGenerator.isAnActionClass(m)) {

            // import method return type if needed
            Class<?> returnType = m.getReturnType();
            //check if the return type is an array
            if (returnType.getComponentType() != null) {
                returnType = returnType.getComponentType();
            }
            if (needsToImportMethodReturnType(returnType)) {
                addImport(imports, returnType, m.getGenericReturnType());
            }

            // import method parameter types if needed
            Class<?> methodParameterTypes[] = m.getParameterTypes();
            Type methodGenericParameterTypes[] = m.getGenericParameterTypes();
            for (int i = 0; i < methodParameterTypes.length; i++) {
                Class<?> methodParameterType = methodParameterTypes[i];
                if (needsToImportMethodParameterType(methodParameterType)) {
                    addImport(imports, methodParameterType, methodGenericParameterTypes[i]);
                }
            }
        }
    }
    if (imports.size() > 0) {
        StringBuilder sb = new StringBuilder();
        for (String s : imports) {
            sb.append(s);
        }
        return sb.toString();
    } else {
        return "";
    }
}
 
Example 13
Project: hy.common.base   File: MethodReflect.java   View Source Code Vote up 5 votes
/**
 * 获取方法某个入参参数上的某个位置的范型Class原型
 * 
 * @param i_Method
 * @param i_ParamIndex      方法的入参参数位置
 * @param i_GenericsIndex   入参参数范型的位置
 * @return
 */
public static Class<?> getGenerics(Method i_Method ,int i_ParamIndex ,int i_GenericsIndex)
{
    try
    {
        ParameterizedType v_PType = (ParameterizedType) i_Method.getGenericParameterTypes()[i_ParamIndex];
        Type              v_Type  = v_PType.getActualTypeArguments()[i_GenericsIndex];
        return (Class<?>)v_Type;
    }
    catch (Exception exce)
    {
        return null;
    }
}
 
Example 14
Project: ghost   File: ArgumentParser.java   View Source Code Vote up 5 votes
@NonNull
static ArgumentParser of(@NonNull final Binder binder, @NonNull final Method method) {
  final Annotation[][] annotations = method.getParameterAnnotations();
  final Type[] types = method.getGenericParameterTypes();

  final Argument[] arguments = new Argument[types.length];
  for(int i = 0; i < types.length; i++) {
    arguments[i] = createArgument(binder, types[i], Arrays.asList(annotations[i]));
  }

  return new ArgumentParser(arguments);
}
 
Example 15
Project: jdk8u-jdk   File: Introspector.java   View Source Code Vote up 5 votes
/**
 * Adds the property descriptor to the list store.
 */
private void addPropertyDescriptor(PropertyDescriptor pd) {
    String propName = pd.getName();
    List<PropertyDescriptor> list = pdStore.get(propName);
    if (list == null) {
        list = new ArrayList<>();
        pdStore.put(propName, list);
    }
    if (this.beanClass != pd.getClass0()) {
        // replace existing property descriptor
        // only if we have types to resolve
        // in the context of this.beanClass
        Method read = pd.getReadMethod();
        Method write = pd.getWriteMethod();
        boolean cls = true;
        if (read != null) cls = cls && read.getGenericReturnType() instanceof Class;
        if (write != null) cls = cls && write.getGenericParameterTypes()[0] instanceof Class;
        if (pd instanceof IndexedPropertyDescriptor) {
            IndexedPropertyDescriptor ipd = (IndexedPropertyDescriptor) pd;
            Method readI = ipd.getIndexedReadMethod();
            Method writeI = ipd.getIndexedWriteMethod();
            if (readI != null) cls = cls && readI.getGenericReturnType() instanceof Class;
            if (writeI != null) cls = cls && writeI.getGenericParameterTypes()[1] instanceof Class;
            if (!cls) {
                pd = new IndexedPropertyDescriptor(ipd);
                pd.updateGenericsFor(this.beanClass);
            }
        }
        else if (!cls) {
            pd = new PropertyDescriptor(pd);
            pd.updateGenericsFor(this.beanClass);
        }
    }
    list.add(pd);
}
 
Example 16
Project: openjdk-jdk10   File: Introspector.java   View Source Code Vote up 5 votes
private boolean isEventHandler(Method m) {
    // We assume that a method is an event handler if it has a single
    // argument, whose type inherit from java.util.Event.
    Type argTypes[] = m.getGenericParameterTypes();
    if (argTypes.length != 1) {
        return false;
    }
    return isSubclass(TypeResolver.erase(TypeResolver.resolveInClass(beanClass, argTypes[0])), EventObject.class);
}
 
Example 17
Project: OpenJSharp   File: ConvertingMethod.java   View Source Code Vote up 5 votes
private ConvertingMethod(Method m) throws OpenDataException {
    this.method = m;
    MXBeanMappingFactory mappingFactory = MXBeanMappingFactory.DEFAULT;
    returnMapping =
            mappingFactory.mappingForType(m.getGenericReturnType(), mappingFactory);
    Type[] params = m.getGenericParameterTypes();
    paramMappings = new MXBeanMapping[params.length];
    boolean identity = true;
    for (int i = 0; i < params.length; i++) {
        paramMappings[i] = mappingFactory.mappingForType(params[i], mappingFactory);
        identity &= DefaultMXBeanMappingFactory.isIdentity(paramMappings[i]);
    }
    paramConversionIsIdentity = identity;
}
 
Example 18
Project: swagger-dubbo   File: DubboHttpController.java   View Source Code Vote up 4 votes
@RequestMapping(value = "/{interfaceClass}/{methodName}/{operationId}", produces = "application/json; charset=utf-8")
@ResponseBody
public ResponseEntity<String> invokeDubbo(@PathVariable("interfaceClass") String interfaceClass,
		@PathVariable("methodName") String methodName,
		@PathVariable("operationId") String operationId, HttpServletRequest request,
		HttpServletResponse response) throws Exception {
	if (!enable) { return new ResponseEntity<String>(HttpStatus.NOT_FOUND); }

	Object ref = null;
	Method method = null;
	Object result = null;
	
	Entry<Class<?>, Object> entry = ReferenceManager.getInstance().getRef(interfaceClass);
	
	if (null == entry){
	    logger.info("No Ref Service FOUND.");
	    return new ResponseEntity<String>(HttpStatus.NOT_FOUND);
	}
	ref = entry.getValue();
	HttpMatch httpMatch = new HttpMatch(entry.getKey(), ref.getClass());
	Method[] interfaceMethods = httpMatch.findInterfaceMethods(methodName);

	if (null != interfaceMethods && interfaceMethods.length > 0) {
		Method[] refMethods = httpMatch.findRefMethods(interfaceMethods, operationId,
				request.getMethod());
		method = httpMatch.matchRefMethod(refMethods, methodName, request.getParameterMap().keySet());
	}
	if (null == method) {
	    logger.info("No Service Method FOUND.");
		return new ResponseEntity<String>(HttpStatus.NOT_FOUND);
	}
	String[] parameterNames = NameDiscover.parameterNameDiscover.getParameterNames(method);
	
	logger.info("[Swagger-dubbo] Invoke by " + cluster);
	if (CLUSTER_RPC.equals(cluster)){
   		ref = ReferenceManager.getInstance().getProxy(interfaceClass);
   		if (null == ref){
   		    logger.info("No Ref Proxy Service FOUND.");
               return new ResponseEntity<String>(HttpStatus.NOT_FOUND);
   		}
   		method = ref.getClass().getMethod(method.getName(), method.getParameterTypes());
   		if (null == method) {
   		    logger.info("No Proxy Service Method FOUND.");
               return new ResponseEntity<String>(HttpStatus.NOT_FOUND);
           }
	}
	logger.debug("[Swagger-dubbo] Invoke dubbo service method:{},parameter:{}", method, Json.pretty(request.getParameterMap()));
	if (null == parameterNames || parameterNames.length == 0) {
		result = method.invoke(ref);
	} else {
		Object[] args = new Object[parameterNames.length];
		Type[] parameterTypes = method.getGenericParameterTypes();
		Class<?>[] parameterClazz = method.getParameterTypes();

		for (int i = 0; i < parameterNames.length; i++) {
			Object suggestPrameterValue = suggestPrameterValue(parameterTypes[i],
					parameterClazz[i], request.getParameter(parameterNames[i]));
			args[i] = suggestPrameterValue;
		}
		result = method.invoke(ref, args);
	}
	return ResponseEntity.ok(Json.mapper().writeValueAsString(result));
}
 
Example 19
Project: jdk8u-jdk   File: StandardMBeanIntrospector.java   View Source Code Vote up 4 votes
@Override
Type[] getGenericParameterTypes(Method m) {
    return m.getGenericParameterTypes();
}
 
Example 20
Project: TakinRPC   File: CGlibProxy.java   View Source Code Vote up 4 votes
public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
    String address = "";
    try {
        InvokeCallback callback = null;
        boolean sync = false;
        //            Stopwatch watch = Stopwatch.createStarted();
        Type[] typeAry = method.getGenericParameterTypes();//ex:java.util.Map<java.lang.String, java.lang.String>
        Class<?>[] clsAry = method.getParameterTypes();//ex:java.util.Map
        if (args == null) {
            args = new Object[0];
        } else {
            for (int i = 0; i < args.length; i++) {
                Class<?> clz = clsAry[i];
                if (clz.isAssignableFrom(InvokeCallback.class)) {
                    sync = true;
                    callback = (InvokeCallback) args[i];
                    break;
                }
            }
        }
        if (args.length != typeAry.length) {
            throw new Exception("argument count error!");
        }
        RemotingProtocol<?> message = new RemotingProtocol<>(localaddress, sequence.getAndIncrement());

        message.setDefineClass(defineClass);
        message.setImplClass(implClass);
        message.setMethod(method.getName());
        message.setArgs(args);
        message.setmParamsTypes(clsAry);
        message.setmReturnType(method.getReturnType());

        address = balance.select(NamingFactory.getInstance().getConfigAddr(serviceName), "");

        if (logger.isDebugEnabled()) {
            logger.debug(String.format("request: %s", JSON.toJSONString(message)));
        }

        if (sync) {
            RemotingNettyClient.getInstance().invokeASync(address, message, 2000, callback);
            return null;
        }
        message = RemotingNettyClient.getInstance().invokeSync(address, message, 2000);

        //            Future<Object> fu = executor.submit(new InvokeThread(address, message));
        //            Object result = fu.get();
        if (logger.isDebugEnabled()) {
            logger.debug(String.format("response: %s", JSON.toJSONString(message)));
        }
        //            logger.info(String.format("invoke sync use:%s", watch.toString()));
        return message.getResultVal();
    } catch (Exception e) {
        logger.error("invoke error", e);
        throw e;
    }
}