List of usage examples for java.lang.reflect Method getParameters
public Parameter[] getParameters()
From source file:lite.flow.util.ActivityInspector.java
static public String[] getArgumentNames(Method method) { String[] names = new String[method.getParameters().length]; for (int i = 0; i < method.getParameters().length; i++) { String name = method.getParameters()[i].getName(); names[i] = name;//w w w. j a v a2 s.com } return names; }
From source file:com.weibo.motan.demo.client.DemoRpcClient.java
public static DubboBenchmark.BenchmarkMessage prepareArgs() throws InvocationTargetException, IllegalAccessException { boolean b = true; int i = 100000; String s = "??"; DubboBenchmark.BenchmarkMessage.Builder builder = DubboBenchmark.BenchmarkMessage.newBuilder(); Method[] methods = builder.getClass().getDeclaredMethods(); for (Method m : methods) { if (m.getName().startsWith("setField") && ((m.getModifiers() & Modifier.PUBLIC) == Modifier.PUBLIC)) { Parameter[] params = m.getParameters(); if (params.length == 1) { String n = params[0].getParameterizedType().getTypeName(); m.setAccessible(true);// ww w . java 2s . co m if (n.endsWith("java.lang.String")) { m.invoke(builder, new Object[] { s }); } else if (n.endsWith("int")) { m.invoke(builder, new Object[] { i }); } else if (n.equals("boolean")) { m.invoke(builder, new Object[] { b }); } } } } return builder.build(); }
From source file:org.apache.tinkerpop.gremlin.jsr223.JavaTranslator.java
private synchronized static void buildMethodCache(final Object delegate, final Map<String, List<Method>> methodCache) { if (methodCache.isEmpty()) { for (final Method method : delegate.getClass().getMethods()) { if (!(method.getName().equals("addV") && method.getParameterCount() == 1 && method.getParameters()[0].getType().equals(Object[].class))) { // hack cause its hard to tell Object[] vs. String :| List<Method> list = methodCache.get(method.getName()); if (null == list) { list = new ArrayList<>(); methodCache.put(method.getName(), list); }/*from w w w .j a v a 2 s . c om*/ list.add(method); } } GLOBAL_METHOD_CACHE.put(delegate.getClass(), methodCache); } }
From source file:plugin.PluginHarness.java
public static void loadPlugins() throws PluginLoadingException { unloadAllPlugins();/*from ww w . j av a 2 s .c o m*/ CommandList.dumpCommands(); File allPlugins = new File("plugins"); if (!allPlugins.exists()) allPlugins.mkdirs(); for (File cPlugin : allPlugins.listFiles()) { String ezName = FilenameUtils.removeExtension(cPlugin.getName()); String pluginLogTag = "[" + ezName + "] "; log.info(pluginLogTag + "Attempting to load plugin"); GroovyClassLoader gcl = new GroovyClassLoader(); try { Class c = gcl.parseClass(cPlugin); Object listenerInst = c.newInstance(); if (!listenerInst.getClass().isAnnotationPresent(PluginInfo.class)) { log.error(pluginLogTag + "Could not load plugin, PluginInfo annotation not present"); continue; } PluginInfo loadPlug = listenerInst.getClass().getAnnotation(PluginInfo.class); boolean plugValid = true; for (Method method : c.getMethods()) { if (method.isAnnotationPresent(CommandTag.class)) { if (method.getParameters().length != 2) { log.error(pluginLogTag + "Method " + method.toGenericString() + " could not be loaded, expected 2 parameters."); plugValid = false; break; } Class<?> eventClazz = method.getParameters()[0].getType(); if (!eventClazz.equals(IMessage.class)) { log.error(pluginLogTag + "Method " + method.toGenericString() + " could not be loaded, parameter 1 should be of type IMessage"); plugValid = false; break; } eventClazz = method.getParameters()[1].getType(); if (!eventClazz.equals(List.class)) { log.error(pluginLogTag + "Method " + method.toGenericString() + " could not be loaded, parameter 2 should be of type List<String>"); plugValid = false; break; } CommandTag cmd = method.getAnnotation(CommandTag.class); // pretty name, scope, command string, description, method CommandList.putC(cmd.prettyName(), cmd.channelScope(), cmd.commandPattern(), cmd.description(), (chatSource, vargs) -> { try { method.invoke(listenerInst, chatSource, vargs); } catch (InvocationTargetException | IllegalAccessException e) { throw e.getCause(); } }); log.info(pluginLogTag + "Registered chat command \"" + cmd.prettyName()); } else if (method.isAnnotationPresent(EventSubscriber.class)) { // validate method signature as being instance of Event if (method.getParameters().length != 1) { log.error(pluginLogTag + "Method " + method.toGenericString() + " could not be loaded, expected only 1 parameter."); plugValid = false; break; } Class<?> eventClazz = method.getParameters()[0].getType(); if (eventClazz.equals(Event.class) || !Event.class.isAssignableFrom(eventClazz)) { log.error(pluginLogTag + "Method " + method.toGenericString() + " could not be loaded, parameter should extend Event"); plugValid = false; break; } } } if (!plugValid) { log.error(pluginLogTag + "One or more errors occurred, loading attempted"); continue; } cli.getDispatcher().registerListener(listenerInst); registeredListeners.add(listenerInst); log.info(pluginLogTag + "Registered listener: " + listenerInst.toString()); log.info(pluginLogTag + "Successfully loaded" + " plugin: \"" + loadPlug.name() + "\" version: \"" + loadPlug.version() + "\" by: \"" + loadPlug.author() + "\""); } catch (Exception e) { log.error(pluginLogTag + "Unknown error occurred", e); } } }
From source file:ch.ifocusit.plantuml.utils.ClassUtils.java
public static Set<Class> getConcernedTypes(Method method) { Set<Class> classes = new HashSet<>(); // manage returned types classes.add(method.getReturnType()); classes.addAll(getGenericTypes(method)); // manage parameters types for (Parameter parameter : method.getParameters()) { classes.addAll(getConcernedTypes(parameter)); }//from ww w . j av a 2s . c o m return classes; }
From source file:org.talend.dataprep.conversions.BeanConversionService.java
/** * The {@link BeanUtils#copyProperties(java.lang.Object, java.lang.Object)} method does <b>NOT</b> check if parametrized type * are compatible when copying values, this helper method performs this additional check and ignore copy of those values. * * @param source The source bean (from which values are read). * @param converted The target bean (to which values are written). *//* www .j a v a 2 s .c o m*/ private static void copyBean(Object source, Object converted) { // Find property(ies) to ignore during copy. List<String> discardedProperties = new LinkedList<>(); final BeanWrapper sourceBean = new BeanWrapperImpl(source); final BeanWrapper targetBean = new BeanWrapperImpl(converted); final PropertyDescriptor[] sourceProperties = sourceBean.getPropertyDescriptors(); for (PropertyDescriptor sourceProperty : sourceProperties) { if (targetBean.isWritableProperty(sourceProperty.getName())) { final PropertyDescriptor targetProperty = targetBean .getPropertyDescriptor(sourceProperty.getName()); final Class<?> sourcePropertyType = sourceProperty.getPropertyType(); final Class<?> targetPropertyType = targetProperty.getPropertyType(); final Method readMethod = sourceProperty.getReadMethod(); if (readMethod != null) { final Type sourceReturnType = readMethod.getGenericReturnType(); final Method targetPropertyWriteMethod = targetProperty.getWriteMethod(); if (targetPropertyWriteMethod != null) { final Type targetReturnType = targetPropertyWriteMethod.getParameters()[0] .getParameterizedType(); boolean valid = Object.class.equals(targetPropertyType) || sourcePropertyType.equals(targetPropertyType) && sourceReturnType.equals(targetReturnType); if (!valid) { discardedProperties.add(sourceProperty.getName()); } } } else { discardedProperties.add(sourceProperty.getName()); } } } // Perform copy BeanUtils.copyProperties(source, converted, discardedProperties.toArray(new String[discardedProperties.size()])); }
From source file:com.github.yongchristophertang.engine.java.LoggerProxyHelper.java
static Object addLogger(Logger logger, Method method, Object[] args, Object client) throws Throwable { if (method.getDeclaringClass() == Object.class) { return method.invoke(client, args); }// w ww .j a va2 s. c o m String formatter = "\n\tAPI: " + method.getName() + "\n\n"; formatter += "\tInput:\n"; for (int i = 0; i < method.getParameterCount(); i++) { formatter += "\t\t" + method.getParameters()[i].getName() + " (" + method.getParameters()[i].getType().getSimpleName() + "): "; if (args[i] == null) { formatter += "NULL"; } else if (args[i] instanceof Iterable) { int cnt = 0; Iterator iter = ((Iterable) args[i]).iterator(); while (iter.hasNext()) { formatter += "\n\t\t\t[" + (++cnt) + "]: " + toPrinterString(iter.next(), false); } } else { formatter += toPrinterString(args[i], false); } formatter += "\n"; } long bf = System.nanoTime(); Object result; try { result = method.invoke(client, args); } catch (InvocationTargetException e) { formatter += "\n\tException: \n\t\t" + e.getTargetException(); formatter += "\n=======================================================================\n"; logger.info(formatter); throw e.getTargetException(); } long af = System.nanoTime(); formatter += "\n\tResponse Time(ms): " + (af - bf) / 1000000 + "\n\n\tOutput:\n"; if (result == null) { formatter += "\t\tNULL\n"; } else if (result instanceof Iterable) { Iterator iter = ((Iterable) result).iterator(); int cnt = 0; while (iter.hasNext()) { formatter += "\t\t[" + (++cnt) + "]: " + toPrinterString(iter.next(), true) + "\n"; } if (cnt == 0) { formatter += "\t\tEmpty Collection []\n"; } } else { formatter += "\t\t" + toPrinterString(result, true) + "\n"; } formatter += "=======================================================================\n"; logger.info(formatter); return result; }
From source file:com.teradata.tempto.internal.ReflectionInjectorHelper.java
public Object[] getMethodArguments(Injector injector, Method method) { if (isAnnotatedWithInject(method)) { Parameter[] parameters = method.getParameters(); Object instance = createInstanceWithFields(parameters); injector.injectMembers(instance); return readFieldValues(instance); } else {/* ww w . j a v a2 s .com*/ return new Object[] {}; } }
From source file:com.newtranx.util.mysql.fabric.SpringMybatisSetShardKeyAspect.java
@Around("@annotation(com.newtranx.util.mysql.fabric.WithShardKey) || @within(com.newtranx.util.mysql.fabric.WithShardKey)") public Object setShardKey(ProceedingJoinPoint pjp) throws Throwable { Method method = AspectJUtils.getMethod(pjp); String key = null;//from www.j a v a2s . c o m boolean force = method.getAnnotation(WithShardKey.class).force(); int i = 0; for (Parameter p : method.getParameters()) { ShardKey a = p.getAnnotation(ShardKey.class); if (a != null) { if (key != null) throw new RuntimeException("found multiple shardkey"); Object obj = pjp.getArgs()[i]; if (StringUtils.isEmpty(a.property())) key = obj.toString(); else { BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(obj); key = bw.getPropertyValue(a.property()).toString(); } } i++; } if (key == null) throw new RuntimeException("can not find shardkey"); fabricShardKey.set(key, force); return pjp.proceed(); }
From source file:nl.kpmg.lcm.server.documentation.MethodDocumentator.java
private String addParameters(Method method, String description) { String parameters = ""; int counter = 1; for (Parameter param : method.getParameters()) { String parameterString = StringUtils.replace(parameterTemplate, "{NUMBER}", Integer.toString(counter)); String annotationString = ""; for (Annotation annotation : param.getAnnotations()) { annotationString += annotation.annotationType().getSimpleName(); }/*from ww w. j av a 2 s . c o m*/ if (annotationString.length() > 0) { annotationString = annotationString + ", "; parameterString = StringUtils.replace(parameterString, "{ANNOTATION}", annotationString); } else { parameterString = StringUtils.replace(parameterString, "{ANNOTATION}", "Payload, "); } parameterString = StringUtils.replace(parameterString, "{TYPE}", "type: " + param.getType().getSimpleName()); parameters += parameterString; counter++; } if (parameters.length() > 0) { parameters = "<br> " + parameters; } else { parameters = "none."; } description = StringUtils.replace(description, "{PARAMETERS}", parameters); return description; }