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

The following are Jave code examples for showing how to use getParameterTypes() 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: adept   File: JdbcHelper.java   View Source Code Vote up 6 votes
/**
 * 将ResultSet转换为指定class的Bean.
 * @param rs ResultSet实例
 * @param rsmd ResultSet元数据
 * @param beanClass 空属性的Bean的class
 * @param propMap Bean属性对应的Map
 * @param <T> 泛型方法
 * @return 值
 * @throws IllegalAccessException IllegalAccessException
 * @throws SQLException SQLException
 * @throws InvocationTargetException InvocationTargetException
 * @throws InstantiationException InstantiationException
 */
public static <T> T getBeanValue(ResultSet rs, ResultSetMetaData rsmd, Class<T> beanClass,
        Map<String, PropertyDescriptor> propMap) throws IllegalAccessException, SQLException,
        InvocationTargetException, InstantiationException {
    T bean = beanClass.newInstance();
    for (int i = 0, cols = rsmd.getColumnCount(); i < cols; i++) {
        String columnName = JdbcHelper.getColumn(rsmd, i + 1);
        if (propMap.containsKey(columnName)) {
            PropertyDescriptor prop = propMap.get(columnName);
            // 获取并调用setter方法.
            Method propSetter = prop.getWriteMethod();
            if (propSetter == null || propSetter.getParameterTypes().length != 1) {
                log.warn("类'{}'的属性'{}'没有标准的setter方法", beanClass.getName(), columnName);
                continue;
            }

            // 得到属性类型并将该数据库列值转成Java对应类型的值
            Class<?> propType = prop.getPropertyType();
            Object value = FieldHandlerChain.newInstance().getColumnValue(rs, i + 1, propType);
            propSetter.invoke(bean, value);
        }
    }
    return bean;
}
 
Example 2
Project: Pogamut3   File: AnnotationListenerRegistrator.java   View Source Code Vote up 6 votes
public LevelDListener(Method method) {
	NullCheck.check(method, "method");
	this.method = method; 
	
	// check the annotation
	if (getAnnotation() == null) {
		throw new ListenerMethodParametersException(method, "There is no ObjectListener annotation on the method!", AnnotationListenerRegistrator.this);				
	}
	
	// check the method signature
	if (method.getParameterTypes().length != 1 ||
	    !method.getParameterTypes()[0].isAssignableFrom(IWorldObjectEvent.class)) { 
		throw new ListenerMethodParametersException(method, method.getAnnotation(ObjectListener.class), AnnotationListenerRegistrator.this);
	}
	
	objectId = getId(method, getAnnotation());
}
 
Example 3
Project: iBase4J-Common   File: Request2ModelUtil.java   View Source Code Vote up 6 votes
/**
 * 根据传递的参数修改数据
 * 
 * @param o
 * @param parameterMap map参数
 */
public static final void covertObjWithMap(Object o, Map<String, String> parameterMap) {
	Class<?> clazz = o.getClass();
	Iterator<Map.Entry<String, String>> iterator = parameterMap.entrySet().iterator();
	while (iterator.hasNext()) {
		Map.Entry<String, String> entry = iterator.next();
		String key = entry.getKey().trim();
		String value = entry.getValue().trim();
		try {
			Method method = setMethod(key, clazz);
			if (method != null) {
				Class<?>[] parameterTypes = method.getParameterTypes();
				if (method != null) {
					Object[] param_value = new Object[] { TypeParseUtil.convert(value, parameterTypes[0], null) };
					method.invoke(o, param_value);
				}
			}
		} catch (Exception e) {
			logger.error("", e);
		}
	}
}
 
Example 4
Project: jsf-sdk   File: InvokeTelnetHandler.java   View Source Code Vote up 6 votes
private static Method findMethod(Class service, String methodName, Object[] args) {
    Method[] methods = service.getMethods();
    Method invokeMethod = null;
    for (Method m : methods) {
        if (m.getName().equals(methodName) && m.getParameterTypes().length == args.length) {
            if (invokeMethod != null) { // 重载
                if (isMatch(invokeMethod.getParameterTypes(), args)) {
                    invokeMethod = m;
                    break;
                }
            } else {
                invokeMethod = m;
            }
        }
    }
    return invokeMethod;
}
 
Example 5
Project: EatDubbo   File: JavaDeserializer.java   View Source Code Vote up 6 votes
/**
  * Returns the readResolve method
  */
 protected Method getReadResolve(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("readResolve") &&
    method.getParameterTypes().length == 0)
  return method;
     }
   }

   return null;
 }
 
Example 6
Project: quickhybrid-android   File: JSBridge.java   View Source Code Vote up 6 votes
/**
 * 获取api类中所有符合要求的api方法并缓存
 *
 * @param injectedCls
 * @return
 * @throws Exception
 */
private static HashMap<String, Method> getAllMethod(Class injectedCls) throws Exception {
    HashMap<String, Method> mMethodsMap = new HashMap<>();
    Method[] methods = injectedCls.getDeclaredMethods();
    for (Method method : methods) {
        String name;
        if (method.getModifiers() != (Modifier.PUBLIC | Modifier.STATIC) || (name = method.getName()) == null) {
            continue;
        }
        Class[] parameters = method.getParameterTypes();
        if (null != parameters && parameters.length == 4) {
            if (parameters[1] == WebView.class && parameters[2] == JSONObject.class && parameters[3] == Callback.class) {
                mMethodsMap.put(name, method);
            }
        }
    }
    return mMethodsMap;
}
 
Example 7
Project: doctemplate   File: PropertyUtils.java   View Source Code Vote up 6 votes
public static Object getProperty(Object bean, String property)
		throws IllegalArgumentException, IllegalAccessException,
		InvocationTargetException, SecurityException, IntrospectionException,
		NoSuchMethodException {
	Object object = null;
	Method getter = getReadMethod(bean.getClass(), property);
	StringTokenizer st = new StringTokenizer(property, "[](,)", false);
	capitalize(st.nextToken());
	Object params[] = new Object[st.countTokens()];
	for (int j = 0; j < params.length; j++) {
		params[j] = st.nextToken();
		if (getter.getParameterTypes()[0] == int.class) {
			params[j] = new Integer((String) params[j]);
		}
	}
	object = getter == null ? null : getter.invoke(bean, params);
	return object;
}
 
Example 8
Project: hadoop   File: WritableRpcEngine.java   View Source Code Vote up 6 votes
public Invocation(Method method, Object[] parameters) {
  this.methodName = method.getName();
  this.parameterClasses = method.getParameterTypes();
  this.parameters = parameters;
  rpcVersion = writableRpcVersion;
  if (method.getDeclaringClass().equals(VersionedProtocol.class)) {
    //VersionedProtocol is exempted from version check.
    clientVersion = 0;
    clientMethodsHash = 0;
  } else {
    this.clientVersion = RPC.getProtocolVersion(method.getDeclaringClass());
    this.clientMethodsHash = ProtocolSignature.getFingerprint(method
        .getDeclaringClass().getMethods());
  }
  this.declaringClassProtocolName = 
      RPC.getProtocolName(method.getDeclaringClass());
}
 
Example 9
Project: jsf-sdk   File: JavaDeserializer.java   View Source Code Vote up 6 votes
/**
  * Returns the readResolve method
  */
 protected Method getReadResolve(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("readResolve") &&
    method.getParameterTypes().length == 0)
  return method;
     }
   }

   return null;
 }
 
Example 10
Project: incubator-netbeans   File: FormEvents.java   View Source Code Vote up 5 votes
private void checkCompatibility(Event event1, Event event2) {
    Method m1 = event1.getListenerMethod();
    Method m2 = event2.getListenerMethod();
    Class[] params1 = m1.getParameterTypes();
    Class[] params2 = m2.getParameterTypes();
    boolean ok;

    if (params1.length == params2.length) {
        ok = true;
        for (int i=0; i < params1.length; i++)
            if (!params1[i].getName().equals(params2[i].getName())) {
                ok = false;
                break;
            }
        if (ok)
            ok = m1.getReturnType().equals(m2.getReturnType());
    }
    else ok = false;

    if (!ok) {
        IllegalArgumentException iae =
            new IllegalArgumentException("Incompatible event"); // NOI18N
        org.openide.ErrorManager.getDefault().annotate(
            iae, FormUtils.getBundleString("MSG_CannotAttach")); // NOI18N
        throw iae;
    }
}
 
Example 11
Project: pooled-jms   File: IntrospectionSupport.java   View Source Code Vote up 5 votes
public static boolean setProperty(Object target, String name, Object value) {
    try {
        Class<?> clazz = target.getClass();
        if (target instanceof SSLServerSocket) {
            // overcome illegal access issues with internal implementation class
            clazz = SSLServerSocket.class;
        }
        Method setter = findSetterMethod(clazz, name);
        if (setter == null) {
            return false;
        }

        // If the type is null or it matches the needed type, just use the
        // value directly
        if (value == null || value.getClass() == setter.getParameterTypes()[0]) {
            setter.invoke(target, value);
        } else {
            // We need to convert it
            setter.invoke(target, convert(value, setter.getParameterTypes()[0]));
        }
        return true;
    } catch (Exception e) {
        LOG.error(String.format("Could not set property %s on %s", name, target), e);
        return false;
    }
}
 
Example 12
Project: firebase-admin-java   File: FirebaseAppTest.java   View Source Code Vote up 5 votes
private static void invokePublicInstanceMethodWithDefaultValues(Object instance, Method method)
    throws InvocationTargetException, IllegalAccessException {
  List<Object> parameters = new ArrayList<>(method.getParameterTypes().length);
  for (Class<?> parameterType : method.getParameterTypes()) {
    parameters.add(Defaults.defaultValue(parameterType));
  }
  method.invoke(instance, parameters.toArray());
}
 
Example 13
Project: ProjectAres   File: MethodParserMap.java   View Source Code Vote up 5 votes
private Record(Object target, Method method) {
    this.target = target;
    this.method = method;

    final TypeToken<?> returnType;
    if(Optional.class.isAssignableFrom(method.getReturnType())) {
        optional = true;
        returnType = Optionals.elementType(method.getGenericReturnType());
    } else {
        optional = false;
        returnType = TypeToken.of(method.getGenericReturnType());
    }

    if(!type.isAssignableFrom(returnType)) {
        throw new IllegalStateException("Method " + method + " return type " + returnType + " is not assignable to " + type);
    }

    if(method.getParameterTypes().length == 0) {
        passElement = false;
    } else  {
        if(!(method.getParameterTypes().length == 1 && Element.class.isAssignableFrom(method.getParameterTypes()[0]))) {
            throw new IllegalStateException("Method " + method + " should take no parameters, or a single Element parameter");
        }
        passElement = true;
    }

    try {
        this.handle = MethodHandleUtils.privateLookup(method.getDeclaringClass())
                                       .unreflect(method)
                                       .bindTo(target);
    } catch(IllegalAccessException e) {
        throw Throwables.propagate(e);
    }
}
 
Example 14
Project: ctsms   File: ArgsUriPart.java   View Source Code Vote up 5 votes
public LinkedHashSet<NamedParameter> getNamedParameters(String resource, boolean excludeOverriden) throws Exception {
	LinkedHashMap<String, NamedParameter> namedParameters = new LinkedHashMap<String, NamedParameter>();
	Method method = getAnnotatedMethod(resource);
	if (method != null) {
		MethodParameterNames annotation = method.getAnnotation(MethodParameterNames.class);
		String[] parameterNames = null;
		if (annotation != null) {
			parameterNames = annotation.value();
		}
		Class[] parameterTypes = method.getParameterTypes();
		if (parameterNames != null && parameterTypes != null) {
			for (int i = 0; i < parameterNames.length; i++) {
				namedParameters.put(parameterNames[i], new NamedParameter(parameterNames[i], parameterTypes[i]));
			}
		}
	}
	Iterator<Entry<String, Object>> it = defaults.entrySet().iterator();
	while (it.hasNext()) {
		Entry<String, Object> defaultParameter = it.next();
		if (!namedParameters.containsKey(defaultParameter.getKey())) {
			namedParameters.put(defaultParameter.getKey(), new NamedParameter(defaultParameter.getKey(), defaultParameter.getValue().getClass()));
		}
	}
	it = overrides.entrySet().iterator();
	while (it.hasNext()) {
		Entry<String, Object> overrideParameter = it.next();
		namedParameters.put(overrideParameter.getKey(), new NamedParameter(overrideParameter.getKey(), overrideParameter.getValue().getClass()));
	}
	if (excludeOverriden) {
		it = overrides.entrySet().iterator();
		while (it.hasNext()) {
			namedParameters.remove(it.next().getKey());
		}
	}
	return new LinkedHashSet<NamedParameter>(namedParameters.values());
}
 
Example 15
Project: lams   File: GenericTypeAwarePropertyDescriptor.java   View Source Code Vote up 5 votes
public GenericTypeAwarePropertyDescriptor(Class<?> beanClass, String propertyName,
		Method readMethod, Method writeMethod, Class<?> propertyEditorClass)
		throws IntrospectionException {

	super(propertyName, null, null);
	this.beanClass = beanClass;
	this.propertyEditorClass = propertyEditorClass;

	Method readMethodToUse = BridgeMethodResolver.findBridgedMethod(readMethod);
	Method writeMethodToUse = BridgeMethodResolver.findBridgedMethod(writeMethod);
	if (writeMethodToUse == null && readMethodToUse != null) {
		// Fallback: Original JavaBeans introspection might not have found matching setter
		// method due to lack of bridge method resolution, in case of the getter using a
		// covariant return type whereas the setter is defined for the concrete property type.
		Method candidate = ClassUtils.getMethodIfAvailable(
				this.beanClass, "set" + StringUtils.capitalize(getName()), (Class<?>[]) null);
		if (candidate != null && candidate.getParameterTypes().length == 1) {
			writeMethodToUse = candidate;
		}
	}
	this.readMethod = readMethodToUse;
	this.writeMethod = writeMethodToUse;

	if (this.writeMethod != null && this.readMethod == null) {
		// Write method not matched against read method: potentially ambiguous through
		// several overloaded variants, in which case an arbitrary winner has been chosen
		// by the JDK's JavaBeans Introspector...
		Set<Method> ambiguousCandidates = new HashSet<Method>();
		for (Method method : beanClass.getMethods()) {
			if (method.getName().equals(writeMethodToUse.getName()) &&
					!method.equals(writeMethodToUse) && !method.isBridge()) {
				ambiguousCandidates.add(method);
			}
		}
		if (!ambiguousCandidates.isEmpty()) {
			this.ambiguousWriteMethods = ambiguousCandidates;
		}
	}
}
 
Example 16
Project: myth   File: MythInvokerInvocationHandler.java   View Source Code Vote up 5 votes
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

    final Myth myth = method.getAnnotation(Myth.class);
    final Class<?>[] arguments = method.getParameterTypes();
    final Class clazz = method.getDeclaringClass();

    if (Objects.nonNull(myth)) {
        final MythTransactionContext mythTransactionContext =
                TransactionContextLocal.getInstance().get();
        try {
            final MythParticipant participant =
                    buildParticipant(mythTransactionContext, myth,
                            method, clazz, args, arguments);
            if (Objects.nonNull(participant)) {
                final MythTransactionManager mythTransactionManager =
                        SpringBeanUtils.getInstance().getBean(MythTransactionManager.class);
                mythTransactionManager.registerParticipant(participant);
            }

            return super.invoke(target, method, args);
        } catch (Throwable throwable) {
            throwable.printStackTrace();
            return getDefaultValue(method.getReturnType());
        }

    } else {
        return super.invoke(target, method, args);
    }


}
 
Example 17
Project: jdk8u-jdk   File: OldMBeanServerTest.java   View Source Code Vote up 4 votes
private static void runTests(
        Callable<MBeanServerConnection> maker, Runnable breaker)
throws Exception {
    for (Method m : OldMBeanServerTest.class.getDeclaredMethods()) {
        if (Modifier.isStatic(m.getModifiers()) &&
                m.getName().startsWith("test") &&
                m.getParameterTypes().length == 0) {
            ExpectException expexc = m.getAnnotation(ExpectException.class);
            mbsc = maker.call();
            try {
                m.invoke(null);
                if (expexc != null) {
                    failure =
                            m.getName() + " did not got expected exception " +
                            expexc.value().getName();
                    System.out.println(failure);
                } else
                    System.out.println(m.getName() + " OK");
            } catch (InvocationTargetException ite) {
                Throwable t = ite.getCause();
                String prob = null;
                if (expexc != null) {
                    if (expexc.value().isInstance(t)) {
                        System.out.println(m.getName() + " OK (got expected " +
                                expexc.value().getName() + ")");
                    } else
                        prob = "got wrong exception";
                } else
                    prob = "got exception";
                if (prob != null) {
                    failure = m.getName() + ": " + prob + " " +
                            t.getClass().getName();
                    System.out.println(failure);
                    t.printStackTrace(System.out);
                }
            } finally {
                if (breaker != null)
                    breaker.run();
            }
        }
    }
}
 
Example 18
Project: JOsu   File: JSONObject.java   View Source Code Vote up 4 votes
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 19
Project: saluki   File: ReflectUtils.java   View Source Code Vote up 4 votes
public static boolean isToStringMethod(Method method) {
  return (method != null && method.getName().equals("toString")
      && method.getParameterTypes().length == 0);
}
 
Example 20
Project: jdk8u-jdk   File: MBeanOperationInfo.java   View Source Code Vote up 4 votes
private static MBeanParameterInfo[] methodSignature(Method method) {
    final Class<?>[] classes = method.getParameterTypes();
    final Annotation[][] annots = method.getParameterAnnotations();
    return parameters(classes, annots);
}