List of usage examples for java.lang.reflect Constructor getParameterCount
public int getParameterCount()
From source file:io.neba.core.resourcemodels.factory.ModelInstantiator.java
/** * @return either the default or an @Inject constructor, if present. Fails if neither a public default constructor nor a public @Inject constructor is * present, of if multiple @Inject constructors exist. *//*from w w w. j a v a 2 s .c o m*/ @SuppressWarnings("unchecked") @Nonnull private static <T> ModelConstructor<T> resolveConstructor(@Nonnull Class<T> modelType) { ModelConstructor<T> constructor; Constructor<T> injectionConstructor = null, defaultConstructor = null; for (Constructor c : modelType.getConstructors()) { if (c.getParameterCount() == 0) { defaultConstructor = c; } if (!annotations(c).containsName(INJECT_ANNOTATION_NAME)) { continue; } if (injectionConstructor != null) { throw new InvalidModelException("Unable to instantiate model " + modelType + ". " + "Found more than one constructor annotated with @Inject: " + injectionConstructor + ", " + c); } injectionConstructor = c; } if (injectionConstructor != null) { Type[] parameters = injectionConstructor.getGenericParameterTypes(); ServiceDependency[] serviceDependencies = new ServiceDependency[parameters.length]; Annotation[][] parameterAnnotations = injectionConstructor.getParameterAnnotations(); for (int i = 0; i < parameters.length; ++i) { Filter filter = findFilterAnnotation(parameterAnnotations[i]); serviceDependencies[i] = new ServiceDependency(parameters[i], modelType, filter); } constructor = new ModelConstructor<>(injectionConstructor, serviceDependencies); } else if (defaultConstructor != null) { constructor = new ModelConstructor<>(defaultConstructor); } else { throw new InvalidModelException("The model " + modelType + " has neither a public default constructor nor a public constructor annotated with @Inject."); } return constructor; }
From source file:com.buffalokiwi.api.APIResponse.java
/** * Clone an api response /*from w ww . j a v a2 s . c om*/ * @param <T> some class that extends APIResponse * @param that Some response to clone * @param type The class * @return A copy of that * @throws java.lang.NoSuchMethodException * @throws java.lang.InstantiationException * @throws java.lang.reflect.InvocationTargetException * @throws java.lang.IllegalAccessException */ public static <T extends APIResponse> T copyFrom(final IAPIResponse that, Class<T> type) throws NoSuchMethodException, InstantiationException, InvocationTargetException, IllegalArgumentException, IllegalAccessException { for (final Constructor<?> c : type.getConstructors()) { if (c.getParameterCount() == 6) { final T r = (T) c.newInstance(that.getProtocolVersion(), that.getStatusLine(), that.headers(), that.getRedirectLocations(), that.getBytes(), that.getResponseCharsetName()); return r; } } //T r = type.getConstructor( ProtocolVersion.class, StatusLine.class, List.class ).newInstance( that.getProtocolVersion(), that.getStatusLine(), that.headers()); //r.setContent( that.getResponseContent(), that.getResponseCharsetName()); //return r; throw new NoSuchMethodException("Failed to locate constructor in class " + type); }
From source file:io.github.benas.randombeans.util.ReflectionUtils.java
private static boolean hasSameArgumentNumber(final Constructor<?> constructor, final RandomizerArgument[] randomizerArguments) { return constructor.getParameterCount() == randomizerArguments.length; }
From source file:sx.blah.discord.SpoofBot.java
/** * Randomly constructs an object.//from w w w . ja v a 2s . c o m * * @param client The discord client. * @param clazz The class to construct. * @param <T> The type of object to construct. * @return The constructed object (or null if not possible). * * @throws IllegalAccessException * @throws InvocationTargetException * @throws InstantiationException */ public static <T> T randomizeObject(IDiscordClient client, Class<T> clazz) throws IllegalAccessException, InvocationTargetException, InstantiationException { if (canBeRandomized(clazz)) { if (String.class.isAssignableFrom(clazz)) return (T) getRandString(); else if (Character.class.isAssignableFrom(clazz)) return (T) getRandCharacter(); else if (Boolean.class.isAssignableFrom(clazz)) return (T) getRandBoolean(); else if (Number.class.isAssignableFrom(clazz)) return (T) getRandNumber((Class<? extends Number>) clazz); else if (Void.class.isAssignableFrom(clazz)) return null; else if (IDiscordClient.class.isAssignableFrom(clazz)) return (T) client; } else { outer: for (Constructor constructor : clazz.getConstructors()) { Object[] parameters = new Object[constructor.getParameterCount()]; for (Class<?> param : constructor.getParameterTypes()) { if (!canBeRandomized(param)) continue outer; } if (parameters.length > 0) { for (int i = 0; i < parameters.length; i++) { parameters[i] = randomizeObject(client, constructor.getParameterTypes()[i]); } return (T) constructor.newInstance(parameters); } else { return (T) constructor.newInstance(); } } } return null; }
From source file:org.jsonschema2pojo.integration.config.UseInnerClassBuildersIT.java
/** * This method confirms that by default the only constructor available to a builder is the empty argument constructor *///w ww . j ava 2s. c om @Test public void innerBuilderExtraConstructorsRequireConfig() throws ClassNotFoundException { ClassLoader resultsClassLoader = schemaRule.generateAndCompile("/schema.useInnerClassBuilders/child.json", "com.example", config("generateBuilders", true, "useInnerClassBuilders", true)); Class<?> builderClass = resultsClassLoader.loadClass("com.example.Child$ChildBuilder"); assertEquals(1, builderClass.getConstructors().length); Constructor<?> constructor = builderClass.getConstructors()[0]; assertEquals(0, constructor.getParameterCount()); }
From source file:com.offbynull.coroutines.instrumenter.asm.InstructionUtils.java
/** * Calls a constructor with a set of arguments. After execution the stack should have an extra item pushed on it: the object that was * created by this constructor./* w ww . ja va2 s . c o m*/ * @param constructor constructor to call * @param args constructor argument instruction lists -- each instruction list must leave one item on the stack of the type expected * by the constructor * @return instructions to invoke a constructor * @throws NullPointerException if any argument is {@code null} or array contains {@code null} * @throws IllegalArgumentException if the length of {@code args} doesn't match the number of parameters in {@code constructor} */ public static InsnList construct(Constructor<?> constructor, InsnList... args) { Validate.notNull(constructor); Validate.notNull(args); Validate.noNullElements(args); Validate.isTrue(constructor.getParameterCount() == args.length); InsnList ret = new InsnList(); Type clsType = Type.getType(constructor.getDeclaringClass()); Type methodType = Type.getType(constructor); ret.add(new TypeInsnNode(Opcodes.NEW, clsType.getInternalName())); ret.add(new InsnNode(Opcodes.DUP)); for (InsnList arg : args) { ret.add(arg); } ret.add(new MethodInsnNode(Opcodes.INVOKESPECIAL, clsType.getInternalName(), "<init>", methodType.getDescriptor(), false)); return ret; }
From source file:org.springframework.web.method.annotation.ModelAttributeMethodProcessor.java
/** * Construct a new attribute instance with the given constructor. * <p>Called from/*from w ww. ja v a2s. c o m*/ * {@link #createAttribute(String, MethodParameter, WebDataBinderFactory, NativeWebRequest)} * after constructor resolution. * @param ctor the constructor to use * @param attributeName the name of the attribute (never {@code null}) * @param binderFactory for creating WebDataBinder instance * @param webRequest the current request * @return the created model attribute (never {@code null}) * @throws BindException in case of constructor argument binding failure * @throws Exception in case of constructor invocation failure * @since 5.0 */ protected Object constructAttribute(Constructor<?> ctor, String attributeName, WebDataBinderFactory binderFactory, NativeWebRequest webRequest) throws Exception { if (ctor.getParameterCount() == 0) { // A single default constructor -> clearly a standard JavaBeans arrangement. return BeanUtils.instantiateClass(ctor); } // A single data class constructor -> resolve constructor arguments from request parameters. ConstructorProperties cp = ctor.getAnnotation(ConstructorProperties.class); String[] paramNames = (cp != null ? cp.value() : parameterNameDiscoverer.getParameterNames(ctor)); Assert.state(paramNames != null, () -> "Cannot resolve parameter names for constructor " + ctor); Class<?>[] paramTypes = ctor.getParameterTypes(); Assert.state(paramNames.length == paramTypes.length, () -> "Invalid number of parameter names: " + paramNames.length + " for constructor " + ctor); Object[] args = new Object[paramTypes.length]; WebDataBinder binder = binderFactory.createBinder(webRequest, null, attributeName); String fieldDefaultPrefix = binder.getFieldDefaultPrefix(); String fieldMarkerPrefix = binder.getFieldMarkerPrefix(); boolean bindingFailure = false; for (int i = 0; i < paramNames.length; i++) { String paramName = paramNames[i]; Class<?> paramType = paramTypes[i]; Object value = webRequest.getParameterValues(paramName); if (value == null) { if (fieldDefaultPrefix != null) { value = webRequest.getParameter(fieldDefaultPrefix + paramName); } if (value == null && fieldMarkerPrefix != null) { if (webRequest.getParameter(fieldMarkerPrefix + paramName) != null) { value = binder.getEmptyValue(paramType); } } } try { MethodParameter methodParam = new MethodParameter(ctor, i); if (value == null && methodParam.isOptional()) { args[i] = (methodParam.getParameterType() == Optional.class ? Optional.empty() : null); } else { args[i] = binder.convertIfNecessary(value, paramType, methodParam); } } catch (TypeMismatchException ex) { ex.initPropertyName(paramName); binder.getBindingErrorProcessor().processPropertyAccessException(ex, binder.getBindingResult()); bindingFailure = true; args[i] = value; } } if (bindingFailure) { if (binder.getBindingResult() instanceof AbstractBindingResult) { AbstractBindingResult result = (AbstractBindingResult) binder.getBindingResult(); for (int i = 0; i < paramNames.length; i++) { result.recordFieldValue(paramNames[i], paramTypes[i], args[i]); } } throw new BindException(binder.getBindingResult()); } return BeanUtils.instantiateClass(ctor, args); }
From source file:org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.java
@Override @Nullable//from www .j a v a 2 s . com public Constructor<?>[] determineCandidateConstructors(Class<?> beanClass, final String beanName) throws BeanCreationException { // Let's check for lookup methods here.. if (!this.lookupMethodsChecked.contains(beanName)) { try { ReflectionUtils.doWithMethods(beanClass, method -> { Lookup lookup = method.getAnnotation(Lookup.class); if (lookup != null) { Assert.state(beanFactory != null, "No BeanFactory available"); LookupOverride override = new LookupOverride(method, lookup.value()); try { RootBeanDefinition mbd = (RootBeanDefinition) beanFactory .getMergedBeanDefinition(beanName); mbd.getMethodOverrides().addOverride(override); } catch (NoSuchBeanDefinitionException ex) { throw new BeanCreationException(beanName, "Cannot apply @Lookup to beans without corresponding bean definition"); } } }); } catch (IllegalStateException ex) { throw new BeanCreationException(beanName, "Lookup method resolution failed", ex); } this.lookupMethodsChecked.add(beanName); } // Quick check on the concurrent map first, with minimal locking. Constructor<?>[] candidateConstructors = this.candidateConstructorsCache.get(beanClass); if (candidateConstructors == null) { // Fully synchronized resolution now... synchronized (this.candidateConstructorsCache) { candidateConstructors = this.candidateConstructorsCache.get(beanClass); if (candidateConstructors == null) { Constructor<?>[] rawCandidates; try { rawCandidates = beanClass.getDeclaredConstructors(); } catch (Throwable ex) { throw new BeanCreationException(beanName, "Resolution of declared constructors on bean Class [" + beanClass.getName() + "] from ClassLoader [" + beanClass.getClassLoader() + "] failed", ex); } List<Constructor<?>> candidates = new ArrayList<>(rawCandidates.length); Constructor<?> requiredConstructor = null; Constructor<?> defaultConstructor = null; Constructor<?> primaryConstructor = BeanUtils.findPrimaryConstructor(beanClass); int nonSyntheticConstructors = 0; for (Constructor<?> candidate : rawCandidates) { if (!candidate.isSynthetic()) { nonSyntheticConstructors++; } else if (primaryConstructor != null) { continue; } AnnotationAttributes ann = findAutowiredAnnotation(candidate); if (ann == null) { Class<?> userClass = ClassUtils.getUserClass(beanClass); if (userClass != beanClass) { try { Constructor<?> superCtor = userClass .getDeclaredConstructor(candidate.getParameterTypes()); ann = findAutowiredAnnotation(superCtor); } catch (NoSuchMethodException ex) { // Simply proceed, no equivalent superclass constructor found... } } } if (ann != null) { if (requiredConstructor != null) { throw new BeanCreationException(beanName, "Invalid autowire-marked constructor: " + candidate + ". Found constructor with 'required' Autowired annotation already: " + requiredConstructor); } boolean required = determineRequiredStatus(ann); if (required) { if (!candidates.isEmpty()) { throw new BeanCreationException(beanName, "Invalid autowire-marked constructors: " + candidates + ". Found constructor with 'required' Autowired annotation: " + candidate); } requiredConstructor = candidate; } candidates.add(candidate); } else if (candidate.getParameterCount() == 0) { defaultConstructor = candidate; } } if (!candidates.isEmpty()) { // Add default constructor to list of optional constructors, as fallback. if (requiredConstructor == null) { if (defaultConstructor != null) { candidates.add(defaultConstructor); } else if (candidates.size() == 1 && logger.isWarnEnabled()) { logger.warn("Inconsistent constructor declaration on bean with name '" + beanName + "': single autowire-marked constructor flagged as optional - " + "this constructor is effectively required since there is no " + "default constructor to fall back to: " + candidates.get(0)); } } candidateConstructors = candidates.toArray(new Constructor<?>[candidates.size()]); } else if (rawCandidates.length == 1 && rawCandidates[0].getParameterCount() > 0) { candidateConstructors = new Constructor<?>[] { rawCandidates[0] }; } else if (nonSyntheticConstructors == 2 && primaryConstructor != null && defaultConstructor != null && !primaryConstructor.equals(defaultConstructor)) { candidateConstructors = new Constructor<?>[] { primaryConstructor, defaultConstructor }; } else if (nonSyntheticConstructors == 1 && primaryConstructor != null) { candidateConstructors = new Constructor<?>[] { primaryConstructor }; } else { candidateConstructors = new Constructor<?>[0]; } this.candidateConstructorsCache.put(beanClass, candidateConstructors); } } } return (candidateConstructors.length > 0 ? candidateConstructors : null); }
From source file:ca.oson.json.Oson.java
<T> T newInstance(Map<String, Object> map, Class<T> valueType) { InstanceCreator creator = getTypeAdapter(valueType); if (creator != null) { return (T) creator.createInstance(valueType); }//from w ww . j a va 2 s.c o m T obj = null; if (valueType != null) { obj = (T) getDefaultValue(valueType); if (obj != null) { return obj; } } if (map == null) { return null; } // @JsonTypeInfo(use = JsonTypeInfo.Id.MINIMAL_CLASS, include = As.PROPERTY, property = "@class") //@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = As.PROPERTY, property = "@class") String JsonClassType = null; if (valueType != null) { if (getAnnotationSupport()) { for (Annotation annotation : valueType.getAnnotations()) { if (annotation instanceof JsonTypeInfo) { JsonTypeInfo jsonTypeInfo = (JsonTypeInfo) annotation; JsonTypeInfo.Id use = jsonTypeInfo.use(); JsonTypeInfo.As as = jsonTypeInfo.include(); if ((use == JsonTypeInfo.Id.MINIMAL_CLASS || use == JsonTypeInfo.Id.CLASS) && as == As.PROPERTY) { JsonClassType = jsonTypeInfo.property(); } } } } } if (JsonClassType == null) { JsonClassType = getJsonClassType(); } String className = null; if (map.containsKey(JsonClassType)) { className = map.get(JsonClassType).toString(); } Class<T> classType = getClassType(className); // && (valueType == null || valueType.isAssignableFrom(classType) || Map.class.isAssignableFrom(valueType)) if (classType != null) { valueType = classType; } if (valueType == null) { return (T) map; // or null, which is better? } Constructor<?>[] constructors = null; Class implClass = null; if (valueType.isInterface() || Modifier.isAbstract(valueType.getModifiers())) { implClass = DeSerializerUtil.implementingClass(valueType.getName()); } if (implClass != null) { constructors = implClass.getDeclaredConstructors(); } else { constructors = valueType.getDeclaredConstructors();//.getConstructors(); } Object singleMapValue = null; Class singleMapValueType = null; if (map.size() == 1) { singleMapValue = map.get(valueType.getName()); if (singleMapValue != null) { singleMapValueType = singleMapValue.getClass(); if (singleMapValueType == String.class) { singleMapValue = StringUtil.unquote(singleMapValue.toString(), isEscapeHtml()); } try { if (valueType == Locale.class) { Constructor constructor = null; String[] parts = ((String) singleMapValue).split("_"); if (parts.length == 1) { constructor = valueType.getConstructor(String.class); constructor.setAccessible(true); obj = (T) constructor.newInstance(singleMapValue); } else if (parts.length == 2) { constructor = valueType.getConstructor(String.class, String.class); constructor.setAccessible(true); obj = (T) constructor.newInstance(parts); } else if (parts.length == 3) { constructor = valueType.getConstructor(String.class, String.class, String.class); constructor.setAccessible(true); obj = (T) constructor.newInstance(parts); } if (obj != null) { return obj; } } } catch (Exception e) { } Map<Class, Constructor> cmaps = new HashMap<>(); for (Constructor constructor : constructors) { //Class[] parameterTypes = constructor.getParameterTypes(); int parameterCount = constructor.getParameterCount(); if (parameterCount == 1) { Class[] types = constructor.getParameterTypes(); cmaps.put(types[0], constructor); } } if (cmaps.size() > 0) { Constructor constructor = null; if ((cmaps.containsKey(Boolean.class) || cmaps.containsKey(boolean.class)) && BooleanUtil.isBoolean(singleMapValue.toString())) { constructor = cmaps.get(Boolean.class); if (constructor == null) { constructor = cmaps.get(boolean.class); } if (constructor != null) { try { constructor.setAccessible(true); obj = (T) constructor .newInstance(BooleanUtil.string2Boolean(singleMapValue.toString())); if (obj != null) { return obj; } } catch (Exception e) { } } } else if (StringUtil.isNumeric(singleMapValue.toString())) { Class[] classes = new Class[] { int.class, Integer.class, long.class, Long.class, double.class, Double.class, Byte.class, byte.class, Short.class, short.class, Float.class, float.class, BigDecimal.class, BigInteger.class, AtomicInteger.class, AtomicLong.class, Number.class }; for (Class cls : classes) { constructor = cmaps.get(cls); if (constructor != null) { try { obj = (T) constructor.newInstance(NumberUtil.getNumber(singleMapValue, cls)); if (obj != null) { return obj; } } catch (Exception e) { } } } } else if (StringUtil.isArrayOrList(singleMapValue.toString()) || singleMapValue.getClass().isArray() || Collection.class.isAssignableFrom(singleMapValue.getClass())) { for (Entry<Class, Constructor> entry : cmaps.entrySet()) { Class cls = entry.getKey(); constructor = entry.getValue(); if (cls.isArray() || Collection.class.isAssignableFrom(cls)) { Object listObject = null; if (singleMapValue instanceof String) { JSONArray objArray = new JSONArray(singleMapValue.toString()); listObject = (List) fromJsonMap(objArray); } else { listObject = singleMapValue; } FieldData objectDTO = new FieldData(listObject, cls, true); listObject = json2Object(objectDTO); if (listObject != null) { try { obj = (T) constructor.newInstance(listObject); if (obj != null) { return obj; } } catch (Exception e) { } } } } } for (Entry<Class, Constructor> entry : cmaps.entrySet()) { Class cls = entry.getKey(); constructor = entry.getValue(); try { obj = (T) constructor.newInstance(singleMapValue); if (obj != null) { return obj; } } catch (Exception e) { } } } } } if (implClass != null) { valueType = implClass; } try { obj = valueType.newInstance(); if (obj != null) { return setSingleMapValue(obj, valueType, singleMapValue, singleMapValueType); } } catch (InstantiationException | IllegalAccessException e) { //e.printStackTrace(); } ///* for (Constructor constructor : constructors) { //Class[] parameterTypes = constructor.getParameterTypes(); int parameterCount = constructor.getParameterCount(); if (parameterCount > 0) { constructor.setAccessible(true); Annotation[] annotations = constructor.getDeclaredAnnotations(); // getAnnotations(); for (Annotation annotation : annotations) { boolean isJsonCreator = false; if (annotation instanceof JsonCreator) { isJsonCreator = true; } else if (annotation instanceof ca.oson.json.annotation.FieldMapper) { ca.oson.json.annotation.FieldMapper fieldMapper = (ca.oson.json.annotation.FieldMapper) annotation; if (fieldMapper.jsonCreator() == BOOLEAN.TRUE) { isJsonCreator = true; } } if (isJsonCreator) { Parameter[] parameters = constructor.getParameters(); String[] parameterNames = ObjectUtil.getParameterNames(parameters); //parameterCount = parameters.length; Object[] parameterValues = new Object[parameterCount]; int i = 0; for (String parameterName : parameterNames) { parameterValues[i] = getParameterValue(map, valueType, parameterName, parameters[i].getType()); i++; } try { obj = (T) constructor.newInstance(parameterValues); if (obj != null) { return setSingleMapValue(obj, valueType, singleMapValue, singleMapValueType); } } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { //e.printStackTrace(); } } } } else { try { constructor.setAccessible(true); obj = (T) constructor.newInstance(); if (obj != null) { return setSingleMapValue(obj, valueType, singleMapValue, singleMapValueType); } } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { //e.printStackTrace(); } } } //*/ // try again for (Constructor constructor : constructors) { int parameterCount = constructor.getParameterCount(); if (parameterCount > 0) { constructor.setAccessible(true); try { List<String> parameterNames = ObjectUtil.getParameterNames(constructor); if (parameterNames != null && parameterNames.size() > 0) { Class[] parameterTypes = constructor.getParameterTypes(); int length = parameterTypes.length; if (length == parameterNames.size()) { Object[] parameterValues = new Object[length]; Object parameterValue; for (int i = 0; i < length; i++) { parameterValues[i] = getParameterValue(map, valueType, parameterNames.get(i), parameterTypes[i]); } try { obj = (T) constructor.newInstance(parameterValues); if (obj != null) { return setSingleMapValue(obj, valueType, singleMapValue, singleMapValueType); } } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { //e.printStackTrace(); } } } } catch (IOException e1) { // e1.printStackTrace(); } } } // try more for (Constructor constructor : constructors) { int parameterCount = constructor.getParameterCount(); if (parameterCount > 0) { constructor.setAccessible(true); Class[] parameterTypes = constructor.getParameterTypes(); List<String> parameterNames; try { parameterNames = ObjectUtil.getParameterNames(constructor); if (parameterNames != null) { int length = parameterTypes.length; if (length > parameterNames.size()) { length = parameterNames.size(); } Object[] parameterValues = new Object[length]; for (int i = 0; i < length; i++) { parameterValues[i] = getParameterValue(map, valueType, parameterNames.get(i), parameterTypes[i]); } obj = (T) constructor.newInstance(parameterValues); if (obj != null) { return setSingleMapValue(obj, valueType, singleMapValue, singleMapValueType); } } } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | IOException e) { //e.printStackTrace(); } } } // try more try { Method[] methods = valueType.getMethods(); // .getMethod("getInstance", null); List<Method> methodList = new ArrayList<>(); if (methods != null) { for (Method method : methods) { String methodName = method.getName(); if (methodName.equals("getInstance") || methodName.equals("newInstance") || methodName.equals("createInstance") || methodName.equals("factory")) { Class returnType = method.getReturnType(); if (valueType.isAssignableFrom(returnType) && Modifier.isStatic(method.getModifiers())) { int parameterCount = method.getParameterCount(); if (parameterCount == 0) { try { obj = ObjectUtil.getMethodValue(null, method); if (obj != null) { return setSingleMapValue(obj, valueType, singleMapValue, singleMapValueType); } } catch (IllegalArgumentException e) { // TODO Auto-generated catch block //e.printStackTrace(); } } else { methodList.add(method); } } } } for (Method method : methodList) { try { int parameterCount = method.getParameterCount(); Object[] parameterValues = new Object[parameterCount]; Object parameterValue; int i = 0; Class[] parameterTypes = method.getParameterTypes(); String[] parameterNames = ObjectUtil.getParameterNames(method); if (parameterCount == 1 && valueType != null && singleMapValue != null && singleMapValueType != null) { if (ObjectUtil.isSameDataType(parameterTypes[0], singleMapValueType)) { try { obj = ObjectUtil.getMethodValue(null, method, singleMapValue); if (obj != null) { return obj; } } catch (IllegalArgumentException ex) { //ex.printStackTrace(); } } } else if (parameterNames != null && parameterNames.length == parameterCount) { for (String parameterName : ObjectUtil.getParameterNames(method)) { parameterValues[i] = getParameterValue(map, valueType, parameterName, parameterTypes[i]); i++; } } else { // try annotation Parameter[] parameters = method.getParameters(); parameterNames = ObjectUtil.getParameterNames(parameters); parameterCount = parameters.length; parameterValues = new Object[parameterCount]; i = 0; for (String parameterName : parameterNames) { parameterValues[i] = getParameterValue(map, valueType, parameterName, parameterTypes[i]); i++; } } obj = ObjectUtil.getMethodValue(null, method, parameterValues); if (obj != null) { return setSingleMapValue(obj, valueType, singleMapValue, singleMapValueType); } } catch (IOException | IllegalArgumentException e) { //e.printStackTrace(); } } } } catch (SecurityException e) { // e.printStackTrace(); } // try all static methods, if the return type is correct, get it as the final object Method[] methods = valueType.getDeclaredMethods(); for (Method method : methods) { if (Modifier.isStatic(method.getModifiers())) { Class returnType = method.getReturnType(); if (valueType.isAssignableFrom(returnType)) { try { Object[] parameterValues = null; int parameterCount = method.getParameterCount(); if (parameterCount > 0) { if (parameterCount == 1 && map.size() == 1 && singleMapValue != null && singleMapValueType != null) { if (ObjectUtil.isSameDataType(method.getParameterTypes()[0], singleMapValueType)) { obj = ObjectUtil.getMethodValue(null, method, singleMapValueType); if (obj != null) { return obj; } } } parameterValues = new Object[parameterCount]; Object parameterValue; int i = 0; Class[] parameterTypes = method.getParameterTypes(); String[] parameterNames = ObjectUtil.getParameterNames(method); if (parameterNames != null && parameterNames.length == parameterCount) { for (String parameterName : ObjectUtil.getParameterNames(method)) { parameterValues[i] = getParameterValue(map, valueType, parameterName, parameterTypes[i]); i++; } } else { // try annotation Parameter[] parameters = method.getParameters(); parameterNames = ObjectUtil.getParameterNames(parameters); parameterCount = parameters.length; parameterValues = new Object[parameterCount]; i = 0; for (String parameterName : parameterNames) { parameterValues[i] = getParameterValue(map, valueType, parameterName, parameterTypes[i]); i++; } } } obj = ObjectUtil.getMethodValue(obj, method, parameterValues); if (obj != null) { return setSingleMapValue(obj, valueType, singleMapValue, singleMapValueType); } } catch (IOException | IllegalArgumentException e) { //e.printStackTrace(); } } } } return null; }