Java Code Examples for java.lang.reflect.Method#getParameterTypes()

The following examples show how to use java.lang.reflect.Method#getParameterTypes() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: HtmlComponentSmokeTest.java    From flow with Apache License 2.0 9 votes vote down vote up
private static boolean isSetter(Method method) {
    if (method.isSynthetic()) {
        return false;
    }
    if (!method.getName().startsWith("set")) {
        return false;
    }

    if (method.getParameterTypes().length != 1) {
        return false;
    }

    int modifiers = method.getModifiers();
    if (Modifier.isStatic(modifiers)) {
        return false;
    }

    if (Modifier.isAbstract(modifiers)) {
        return false;
    }

    return true;
}
 
Example 2
Source File: MetadataMBeanInfoAssembler.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * Reads {@code MBeanParameterInfo} from the {@code ManagedOperationParameter}
 * attributes attached to a method. Returns an empty array of {@code MBeanParameterInfo}
 * if no attributes are found.
 */
@Override
protected MBeanParameterInfo[] getOperationParameters(Method method, String beanKey) {
	ManagedOperationParameter[] params = obtainAttributeSource().getManagedOperationParameters(method);
	if (ObjectUtils.isEmpty(params)) {
		return super.getOperationParameters(method, beanKey);
	}

	MBeanParameterInfo[] parameterInfo = new MBeanParameterInfo[params.length];
	Class<?>[] methodParameters = method.getParameterTypes();
	for (int i = 0; i < params.length; i++) {
		ManagedOperationParameter param = params[i];
		parameterInfo[i] =
				new MBeanParameterInfo(param.getName(), methodParameters[i].getName(), param.getDescription());
	}
	return parameterInfo;
}
 
Example 3
Source File: BeanDeserializer.java    From joyrpc with Apache License 2.0 6 votes vote down vote up
/**
 * Finds any matching setter.
 */
private Method findGetter(Method[] methods, String setterName, Class arg) {
    String getterName = "get" + setterName.substring(3);

    for (int i = 0; i < methods.length; i++) {
        Method method = methods[i];

        if (!method.getName().equals(getterName)) {
            continue;
        }

        if (!method.getReturnType().equals(arg)) {
            continue;
        }

        Class[] params = method.getParameterTypes();

        if (params.length == 0) {
            return method;
        }
    }

    return null;
}
 
Example 4
Source File: BeanSerializer.java    From sofa-hessian with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the writeReplace method
 */
protected Method getWriteReplace(Class cl)
{
    for (; cl != null; cl = cl.getSuperclass()) {
        Method[] methods = cl.getDeclaredMethods();

        for (int i = 0; i < methods.length; i++) {
            Method method = methods[i];

            if (method.getName().equals("writeReplace") &&
                method.getParameterTypes().length == 0)
                return method;
        }
    }

    return null;
}
 
Example 5
Source File: MethodComparator.java    From cxf with Apache License 2.0 6 votes vote down vote up
public int compare(Method m1, Method m2) {

        int val = m1.getName().compareTo(m2.getName());
        if (val == 0) {
            val = m1.getParameterTypes().length - m2.getParameterTypes().length;
            if (val == 0) {
                Class<?>[] types1 = m1.getParameterTypes();
                Class<?>[] types2 = m2.getParameterTypes();
                for (int i = 0; i < types1.length; i++) {
                    val = types1[i].getName().compareTo(types2[i].getName());

                    if (val != 0) {
                        break;
                    }
                }
            }
        }
        return val;
    }
 
Example 6
Source File: Introspector.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Returns {@code true} if the given method is a "getter" method (where
 * "getter" method is a public method of the form getXXX or "boolean
 * isXXX")
 */
static boolean isReadMethod(Method method) {
    // ignore static methods
    int modifiers = method.getModifiers();
    if (Modifier.isStatic(modifiers))
        return false;

    String name = method.getName();
    Class<?>[] paramTypes = method.getParameterTypes();
    int paramCount = paramTypes.length;

    if (paramCount == 0 && name.length() > 2) {
        // boolean isXXX()
        if (name.startsWith(IS_METHOD_PREFIX))
            return (method.getReturnType() == boolean.class);
        // getXXX()
        if (name.length() > 3 && name.startsWith(GET_METHOD_PREFIX))
            return (method.getReturnType() != void.class);
    }
    return false;
}
 
Example 7
Source File: ReflectionUtils.java    From aws-sdk-java-resources with Apache License 2.0 6 votes vote down vote up
/**
 * Finds a method of the given name that will accept a parameter of the
 * given type. If more than one method matches, returns the first such
 * method found.
 *
 * @param target the object to reflect on
 * @param name the name of the method to search for
 * @param parameterType the type of the parameter to be passed
 * @return the matching method
 * @throws IllegalStateException if no matching method is found
 */
private static Method findMethod(
        Object target,
        String name,
        Class<?> parameterType) {

    for (Method method : target.getClass().getMethods()) {
        if (!method.getName().equals(name)) {
            continue;
        }

        Class<?>[] parameters = method.getParameterTypes();
        if (parameters.length != 1) {
            continue;
        }

        if (parameters[0].isAssignableFrom(parameterType)) {
            return method;
        }
    }

    throw new IllegalStateException(
            "No method '" + name + "(" + parameterType + ") on type "
            + target.getClass());
}
 
Example 8
Source File: PolicyImpl.java    From gravitee-gateway with Apache License 2.0 6 votes vote down vote up
private Object invoke(Method invokedMethod, Object ... args) throws PolicyException {
    if (invokedMethod != null) {
        Class<?>[] parametersType = invokedMethod.getParameterTypes();
        Object[] parameters = new Object[parametersType.length];

        int idx = 0;

        // Map parameters according to parameter's type
        for (Class<?> paramType : parametersType) {
            parameters[idx++] = getParameterAssignableTo(paramType, args);
        }

        try {
            return invokedMethod.invoke(policyInst, parameters);
        } catch (Exception ex) {
            throw new PolicyException(ex);
        }
    }

    return null;
}
 
Example 9
Source File: MBeanAnalyzer.java    From JDKSourceCode1.8 with MIT License 6 votes vote down vote up
public int compare(Method a, Method b) {
    final int cmp = a.getName().compareTo(b.getName());
    if (cmp != 0) return cmp;
    final Class<?>[] aparams = a.getParameterTypes();
    final Class<?>[] bparams = b.getParameterTypes();
    if (aparams.length != bparams.length)
        return aparams.length - bparams.length;
    if (!Arrays.equals(aparams, bparams)) {
        return Arrays.toString(aparams).
                compareTo(Arrays.toString(bparams));
    }
    final Class<?> aret = a.getReturnType();
    final Class<?> bret = b.getReturnType();
    if (aret == bret) return 0;

    // Super type comes first: Object, Number, Integer
    if (aret.isAssignableFrom(bret))
        return -1;
    return +1;      // could assert bret.isAssignableFrom(aret)
}
 
Example 10
Source File: DefaultMXBeanMappingFactory.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
public static String propertyName(Method m) {
    String rest = null;
    String name = m.getName();
    if (name.startsWith("get"))
        rest = name.substring(3);
    else if (name.startsWith("is") && m.getReturnType() == boolean.class)
        rest = name.substring(2);
    if (rest == null || rest.length() == 0
        || m.getParameterTypes().length > 0
        || m.getReturnType() == void.class
        || name.equals("getClass"))
        return null;
    return rest;
}
 
Example 11
Source File: ScriptValuesMetaModDialog.java    From hop with Apache License 2.0 5 votes vote down vote up
private String buildAddClassFunctionName( Method metForParams ) {
  StringBuilder sbRC = new StringBuilder();
  String strRC = "";
  Class<?>[] clsParamType = metForParams.getParameterTypes();
  String strParam;

  for ( int x = 0; x < clsParamType.length; x++ ) {
    strParam = clsParamType[ x ].getName();
    if ( strParam.toLowerCase().indexOf( "javascript" ) <= 0 ) {
      if ( strParam.toLowerCase().indexOf( "object" ) > 0 ) {
        sbRC.append( "var" );
        sbRC.append( ", " );
      } else if ( strParam.equals( "java.lang.String" ) ) {
        sbRC.append( "String" );
        sbRC.append( ", " );
      } else {
        sbRC.append( strParam );
        sbRC.append( ", " );
      }
    }

  }
  strRC = sbRC.toString();
  if ( strRC.length() > 0 ) {
    strRC = strRC.substring( 0, sbRC.length() - 2 );
  }
  return strRC;
}
 
Example 12
Source File: ReflectUtils.java    From dubbox with Apache License 2.0 5 votes vote down vote up
/**
 * get method desc.
 * int do(int arg1) => "do(I)I"
 * void do(String arg1,boolean arg2) => "do(Ljava/lang/String;Z)V"
 * 
 * @param m method.
 * @return desc.
 */
public static String getDesc(final Method m)
{
	StringBuilder ret = new StringBuilder(m.getName()).append('(');
	Class<?>[] parameterTypes = m.getParameterTypes();
	for(int i=0;i<parameterTypes.length;i++)
		ret.append(getDesc(parameterTypes[i]));
	ret.append(')').append(getDesc(m.getReturnType()));
	return ret.toString();
}
 
Example 13
Source File: LuaReflectionHelper.java    From OpenPeripheral with MIT License 5 votes vote down vote up
private static Map<String, Object> describe(Method method) {
	Map<String, Object> desc = Maps.newHashMap();

	List<String> args = Lists.newArrayList();
	for (Class<?> arg : method.getParameterTypes())
		args.add(arg.toString());

	desc.put("modifiers", Modifier.toString(method.getModifiers()));
	desc.put("from", method.getDeclaringClass().toString());

	desc.put("args", args);
	return desc;
}
 
Example 14
Source File: SmackIntegrationTestFramework.java    From Smack with Apache License 2.0 5 votes vote down vote up
static boolean testMethodParametersIsListOfConnections(Method testMethod, Class<? extends AbstractXMPPConnection> connectionClass) {
    Type[] parameterTypes = testMethod.getGenericParameterTypes();
    if (parameterTypes.length != 1) {
        return false;
    }
    Class<?> soleParameter = testMethod.getParameterTypes()[0];
    if (!Collection.class.isAssignableFrom(soleParameter)) {
        return false;
    }

    ParameterizedType soleParameterizedType = (ParameterizedType) parameterTypes[0];
    Type[] actualTypeArguments = soleParameterizedType.getActualTypeArguments();
    if (actualTypeArguments.length != 1) {
        return false;
    }

    Type soleActualTypeArgument = actualTypeArguments[0];
    if (!(soleActualTypeArgument instanceof Class<?>)) {
        return false;
    }
    Class<?> soleActualTypeArgumentAsClass = (Class<?>) soleActualTypeArgument;
    if (!connectionClass.isAssignableFrom(soleActualTypeArgumentAsClass)) {
        return false;
    }

    return true;
}
 
Example 15
Source File: Type.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Returns the descriptor corresponding to the given method.
 *
 * @param m
 *            a {@link Method Method} object.
 * @return the descriptor of the given method.
 */
public static String getMethodDescriptor(final Method m) {
    Class<?>[] parameters = m.getParameterTypes();
    StringBuffer buf = new StringBuffer();
    buf.append('(');
    for (int i = 0; i < parameters.length; ++i) {
        getDescriptor(buf, parameters[i]);
    }
    buf.append(')');
    getDescriptor(buf, m.getReturnType());
    return buf.toString();
}
 
Example 16
Source File: ReflectionHelper.java    From Concurnas with MIT License 5 votes vote down vote up
public static int getParameterCount(Method meth){
	Class<?>[] ret = meth.getParameterTypes();
	int len = ret.length;
	if(len == 0){
		return 0;
	}else if(ret[len-1]==Fiber.class){
		return len-1;
	}
	return len;
}
 
Example 17
Source File: JSONObject.java    From browserprint with MIT License 4 votes vote down vote up
private void populateMap(Object bean) {
        Class<?> klass = bean.getClass();

// If klass is a System class then set includeSuperClass to false.

        boolean includeSuperClass = klass.getClassLoader() != null;

        Method[] methods = includeSuperClass ? klass.getMethods() : klass
                .getDeclaredMethods();
        for (int i = 0; i < methods.length; i += 1) {
            try {
                Method method = methods[i];
                if (Modifier.isPublic(method.getModifiers())) {
                    String name = method.getName();
                    String key = "";
                    if (name.startsWith("get")) {
                        if ("getClass".equals(name)
                                || "getDeclaringClass".equals(name)) {
                            key = "";
                        } else {
                            key = name.substring(3);
                        }
                    } else if (name.startsWith("is")) {
                        key = name.substring(2);
                    }
                    if (key.length() > 0
                            && Character.isUpperCase(key.charAt(0))
                            && method.getParameterTypes().length == 0) {
                        if (key.length() == 1) {
                            key = key.toLowerCase();
                        } else if (!Character.isUpperCase(key.charAt(1))) {
                            key = key.substring(0, 1).toLowerCase()
                                    + key.substring(1);
                        }

                        Object result = method.invoke(bean, (Object[]) null);
                        if (result != null) {
                            this.map.put(key, wrap(result));
                        }
                    }
                }
            } catch (Exception ignore) {
            }
        }
    }
 
Example 18
Source File: KurentoTestWatcher.java    From kurento-java with Apache License 2.0 4 votes vote down vote up
public static void invokeMethods(List<Method> methods, Class<? extends Annotation> annotation,
    Throwable throwable, Description description) {
  for (Method method : methods) {
    log.debug("Invoking method {} annotated with {}", method, annotation);

    try {
      if (!Modifier.isPublic(method.getModifiers())) {
        log.warn("Method {} is not public and it cannot be invoked", method);
        continue;
      }

      if (!Modifier.isStatic(method.getModifiers())) {
        log.warn("Method {} is not static and it cannot be invoked", method);
        continue;
      }

      Class<?>[] parameterTypes = method.getParameterTypes();

      switch (parameterTypes.length) {
        case 0:
          method.invoke(null);
          break;

        case 1:
          if (parameterTypes[0].equals(Throwable.class)) {
            method.invoke(null, throwable);
          } else if (parameterTypes[0].equals(Description.class)) {
            method.invoke(null, description);
          } else {
            log.warn("Method {} annotated with {} cannot be invoked." + " Incorrect argument: {}",
                method, annotation, parameterTypes[0]);
          }
          break;

        case 2:
          Object param1 = parameterTypes[0].equals(Throwable.class) ? throwable
              : parameterTypes[0].equals(Description.class) ? description : null;
          Object param2 = parameterTypes[1].equals(Throwable.class) ? throwable
              : parameterTypes[1].equals(Description.class) ? description : null;

          if (param1 != null && param2 != null) {
            method.invoke(null, param1, param2);
          } else {
            log.warn(
                "Method {} annotated with {} cannot be invoked." + " Incorrect arguments: {}, {}",
                method, annotation, parameterTypes[0], parameterTypes[1]);
          }
          break;

        default:
          log.warn("Method {} annotated with {} cannot be invoked." + " Incorrect arguments: {}",
              method, annotation, Arrays.toString(parameterTypes));
          break;
      }

    } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
      log.warn("Exception invoking method {} annotated with {}: {} {}", method, e.getClass(),
          e.getMessage());
    }
  }
}
 
Example 19
Source File: RpcInvocation.java    From dubbox with Apache License 2.0 4 votes vote down vote up
public RpcInvocation(Method method, Object[] arguments) {
    this(method.getName(), method.getParameterTypes(), arguments, null, null);
}
 
Example 20
Source File: MethodPartFactory.java    From simplexml with Apache License 2.0 3 votes vote down vote up
/**
 * This is the parameter type associated with the provided method.
 * The first parameter is returned if the provided method is a
 * setter. If the method takes more than one parameter or if it
 * takes no parameters then null is returned from this.
 * 
 * @param method this is the method to get the parameter type for
 * 
 * @return this returns the parameter type associated with it
 */
private Class getParameterType(Method method) throws Exception {
   Class[] list = method.getParameterTypes();
   
   if(list.length == 1) {
      return method.getParameterTypes()[0];
   }
   return null;
}