List of usage examples for java.lang.reflect Method toGenericString
@Override
public String toGenericString()
From source file:kenh.expl.impl.BaseFunction.java
/** * Find the method with name <code>process</code> or <code>@Processing</code> *///from w ww. j a v a 2 s . com @Override public Object invoke(Object... params) throws UnsupportedExpressionException { Method[] methods = this.getClass().getMethods(); for (Method method : methods) { String name = method.getName(); Class[] classes = method.getParameterTypes(); Annotation a = method.getAnnotation(Processing.class); if ((name.equals(METHOD) || a != null) && params.length == classes.length) { logger.trace("Method: " + method.toGenericString()); boolean find = true; Object[] objs = new Object[params.length]; for (int i = 0; i < params.length; i++) { Class class1 = params[i].getClass(); Class class2 = classes[i]; if (class2.isAssignableFrom(class1) || class2 == Object.class) { objs[i] = params[i]; } else if (class1 == String.class) { try { Object obj = Environment.convert((String) params[i], class2); if (obj == null) { logger.trace("Failure(Convert failure[" + (i + 1) + "-" + class1 + "," + class2 + "]): " + method.toGenericString()); find = false; break; } else { objs[i] = obj; } } catch (Exception e) { logger.trace("Failure(Convert exception[" + (i + 1) + "-" + e.getMessage() + "]): " + method.toGenericString()); find = false; break; //UnsupportedExpressionException ex = new UnsupportedExpressionException(e); //throw ex; } } else { logger.trace("Failure(Class unmatched[" + (i + 1) + "]): " + method.toGenericString()); find = false; break; } } if (find) { try { return method.invoke(this, objs); } catch (Exception e) { if (e instanceof UnsupportedExpressionException) throw (UnsupportedExpressionException) e; else throw new UnsupportedExpressionException(e); } } } } String paramStr = ""; for (Object param : params) { paramStr += param.getClass().getCanonicalName() + ", "; } paramStr = StringUtils.defaultIfBlank(StringUtils.chop(StringUtils.trimToEmpty(paramStr)), "<NO PARAM>"); UnsupportedExpressionException e = new UnsupportedExpressionException( "Can't find the method to process.[" + paramStr + "]"); throw e; }
From source file:candr.yoclip.option.OptionSetter.java
/** * Initializes the method descriptor to create an association between the bean setter {@code Method} and the {@code Option} * annotation.// w w w. j a v a2 s . c om * * @param option The annotation associated with the bean setter method. * @param setter The bean setter method annotated with {@code Option}. * @throws OptionsBadNameException if one of the option {@link Option#name() name} is empty or the option does not have at * least one name. * @throws UnsupportedOperationException if the setter method requires more than one parameter. */ public OptionSetter(final Option option, final Method setter) { super(setter); final Class<?>[] parameterTypes = setter.getParameterTypes(); if (1 != parameterTypes.length) { throw new UnsupportedOperationException(setter.toGenericString() + " must have 1 parameter."); } for (final String name : option.name()) { if (StringUtils.isEmpty(name)) { throw new OptionsBadNameException(setter.getName() + " has an option name that is empty."); } } if (option.name().length == 0) { throw new OptionsBadNameException("Options must have at least one name."); } this.option = option; }
From source file:org.springframework.aop.interceptor.AsyncExecutionInterceptor.java
/** * Handles a fatal error thrown while asynchronously invoking the specified * {@link Method}.//from www . j a v a 2 s. c om * <p>If the return type of the method is a {@link Future} object, the original * exception can be propagated by just throwing it at the higher level. However, * for all other cases, the exception will not be transmitted back to the client. * In that later case, the current {@link AsyncUncaughtExceptionHandler} will be * used to manage such exception. * @param ex the exception to handle * @param method the method that was invoked * @param params the parameters used to invoke the method */ protected void handleError(Throwable ex, Method method, Object... params) throws Exception { if (method.getReturnType().isAssignableFrom(Future.class)) { ReflectionUtils.rethrowException(ex); } else { // Could not transmit the exception to the caller with default executor try { this.exceptionHandler.handleUncaughtException(ex, method, params); } catch (Throwable ex2) { logger.error("Exception handler for async method '" + method.toGenericString() + "' threw unexpected exception itself", ex2); } } }
From source file:com.astamuse.asta4d.util.annotation.AnnotatedPropertyUtil.java
@SuppressWarnings({ "rawtypes", "unchecked" }) private static AnnotatedPropertyInfoMap retrievePropertiesMap(Class cls) { String cacheKey = cls.getName(); AnnotatedPropertyInfoMap map = propertiesMapCache.get(cacheKey); if (map == null) { List<AnnotatedPropertyInfo> infoList = new LinkedList<>(); Set<String> beanPropertyNameSet = new HashSet<>(); Method[] mtds = cls.getMethods(); for (Method method : mtds) { List<Annotation> annoList = ConvertableAnnotationRetriever .retrieveAnnotationHierarchyList(AnnotatedProperty.class, method.getAnnotations()); if (CollectionUtils.isEmpty(annoList)) { continue; }/* w w w .java 2 s. c om*/ AnnotatedPropertyInfo info = new AnnotatedPropertyInfo(); info.setAnnotations(annoList); boolean isGet = false; boolean isSet = false; String propertySuffixe = method.getName(); if (propertySuffixe.startsWith("set")) { propertySuffixe = propertySuffixe.substring(3); isSet = true; } else if (propertySuffixe.startsWith("get")) { propertySuffixe = propertySuffixe.substring(3); isGet = true; } else if (propertySuffixe.startsWith("is")) { propertySuffixe = propertySuffixe.substring(2); isSet = true; } else { String msg = String.format("Method [%s]:[%s] can not be treated as a getter or setter method.", cls.getName(), method.toGenericString()); throw new RuntimeException(msg); } char[] cs = propertySuffixe.toCharArray(); cs[0] = Character.toLowerCase(cs[0]); info.setBeanPropertyName(new String(cs)); AnnotatedProperty ap = (AnnotatedProperty) annoList.get(0);// must by String name = ap.name(); if (StringUtils.isEmpty(name)) { name = info.getBeanPropertyName(); } info.setName(name); if (isGet) { info.setGetter(method); info.setType(method.getReturnType()); String setterName = "set" + propertySuffixe; Method setter = null; try { setter = cls.getMethod(setterName, method.getReturnType()); } catch (NoSuchMethodException | SecurityException e) { String msg = "Could not find setter method:[{}({})] in class[{}] for annotated getter:[{}]"; logger.warn(msg, new Object[] { setterName, method.getReturnType().getName(), cls.getName(), method.getName() }); } info.setSetter(setter); } if (isSet) { info.setSetter(method); info.setType(method.getParameterTypes()[0]); String getterName = "get" + propertySuffixe; Method getter = null; try { getter = cls.getMethod(getterName); } catch (NoSuchMethodException | SecurityException e) { String msg = "Could not find getter method:[{}:{}] in class[{}] for annotated setter:[{}]"; logger.warn(msg, new Object[] { getterName, method.getReturnType().getName(), cls.getName(), method.getName() }); } info.setGetter(getter); } infoList.add(info); beanPropertyNameSet.add(info.getBeanPropertyName()); } List<Field> list = new ArrayList<>(ClassUtil.retrieveAllFieldsIncludeAllSuperClasses(cls)); Iterator<Field> it = list.iterator(); while (it.hasNext()) { Field f = it.next(); List<Annotation> annoList = ConvertableAnnotationRetriever .retrieveAnnotationHierarchyList(AnnotatedProperty.class, f.getAnnotations()); if (CollectionUtils.isNotEmpty(annoList)) { AnnotatedProperty ap = (AnnotatedProperty) annoList.get(0);// must by String beanPropertyName = f.getName(); if (beanPropertyNameSet.contains(beanPropertyName)) { continue; } String name = ap.name(); if (StringUtils.isEmpty(name)) { name = f.getName(); } AnnotatedPropertyInfo info = new AnnotatedPropertyInfo(); info.setAnnotations(annoList); info.setBeanPropertyName(beanPropertyName); info.setName(name); info.setField(f); info.setGetter(null); info.setSetter(null); info.setType(f.getType()); infoList.add(info); } } map = new AnnotatedPropertyInfoMap(infoList); if (Configuration.getConfiguration().isCacheEnable()) { propertiesMapCache.put(cacheKey, map); } } return map; }
From source file:nats.client.spring.AnnotationConfigBeanPostProcessor.java
@Override public Object postProcessAfterInitialization(final Object bean, String beanName) throws BeansException { final Class<?> clazz = bean.getClass(); for (final Method method : clazz.getMethods()) { final Subscribe annotation = AnnotationUtils.findAnnotation(method, Subscribe.class); if (annotation != null) { final Class<?>[] parameterTypes = method.getParameterTypes(); if (parameterTypes.length != 1 || !parameterTypes[0].equals(Message.class)) { throw new BeanInitializationException(String.format( "Method '%s' on bean with name '%s' must have a single parameter of type %s when using the @%s annotation.", method.toGenericString(), beanName, Message.class.getName(), Subscribe.class.getName())); }//from ww w .j av a 2s . co m nats.subscribe(annotation.value()).addMessageHandler(new MessageHandler() { @Override public void onMessage(Message message) { try { method.invoke(bean, message); } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (InvocationTargetException e) { final Throwable targetException = e.getTargetException(); if (targetException instanceof RuntimeException) { throw (RuntimeException) targetException; } throw new RuntimeException(targetException); } } }); } } return bean; }
From source file:com.github.steveash.typedconfig.ConfigFactoryContext.java
private String getLocalConfigKey(Method method, Config config) { if (!config.value().equals("")) return config.value(); if (PropertyUtil.isProperty(method)) { return Preconditions.checkNotNull(PropertyUtil.getPropertyName(method)); }/*from w w w . j ava 2 s .c o m*/ int argsCount = method.getParameterTypes().length; if (argsCount == 0) { return method.getName(); // default to the name. should we allow this? } throw new IllegalArgumentException( "Method " + method.toGenericString() + " takes > 0 parameters which " + "is not supported."); }
From source file:net.sourceforge.stripes.integration.spring.SpringHelper.java
/** * Fetches the methods on a class that are annotated with SpringBean. The first time it * is called for a particular class it will introspect the class and cache the results. * All non-overridden methods are examined, including protected and private methods. * If a method is not public an attempt it made to make it accessible - if it fails * it is removed from the collection and an error is logged. * * @param clazz the class on which to look for SpringBean annotated methods * @return the collection of methods with the annotation *//*ww w . j a v a 2s . c o m*/ protected static Collection<Method> getMethods(Class<?> clazz) { Collection<Method> methods = methodMap.get(clazz); if (methods == null) { methods = ReflectUtil.getMethods(clazz); Iterator<Method> iterator = methods.iterator(); while (iterator.hasNext()) { Method method = iterator.next(); if (!method.isAnnotationPresent(SpringBean.class)) { iterator.remove(); } else { // If the method isn't public, try to make it accessible if (!method.isAccessible()) { try { method.setAccessible(true); } catch (SecurityException se) { throw new StripesRuntimeException("Method " + clazz.getName() + "." + method.getName() + "is marked " + "with @SpringBean and is not public. An attempt to call " + "setAccessible(true) resulted in a SecurityException. Please " + "either make the method public or modify your JVM security " + "policy to allow Stripes to setAccessible(true).", se); } } // Ensure the method has only the one parameter if (method.getParameterTypes().length != 1) { throw new StripesRuntimeException( "A method marked with @SpringBean must have exactly one parameter: " + "the bean to be injected. Method [" + method.toGenericString() + "] has " + method.getParameterTypes().length + " parameters."); } } } methodMap.put(clazz, methods); } return methods; }
From source file:net.sf.jdbcwrappers.trim.TrimmingResultSetInvocationHandler.java
@Override /**// w w w . j a v a 2 s .com * Modifies getObject and getString behavior. * If the column is of type <tt>CHAR</tt>, the returned object is * a {@link String} holding the column value without trailing spaces. */ public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { MethodInvocation methodInvocation = new MethodInvocation(target, method, args); Object result = methodInvocation.invoke(); if (result instanceof String && ("getObject".equals(method.getName()) || "getString".equals(method.getName()))) { String stringResult = (String) result; if (method.getParameterTypes().length < 1) { throw new IllegalStateException( "Method signature not expected on class ResultSet: " + method.toGenericString()); } if (int.class.equals(method.getParameterTypes()[0])) { int columnIndex = (Integer) args[0]; return isCharColumn(columnIndex) ? trim(stringResult) : stringResult; } else if (String.class.equals(method.getParameterTypes()[0])) { String columnLabel = (String) args[0]; return isCharColumn(columnLabel) ? trim(stringResult) : stringResult; } else { throw new IllegalStateException( "Method signature not expected on class ResultSet: " + method.toGenericString()); } } else { Class<?> clazz = ProxyHelper.getJdbcClass(result); if (clazz != null && !ProxyHelper.isWrapped(result, TrimmingResultSetInvocationHandler.class) && !ProxyHelper.isWrapped(result, TrimmingDelegateInvocationHandler.class)) { return ProxyHelper.createProxy(clazz, new TrimmingDelegateInvocationHandler<Object>(result)); } else { return result; } } }
From source file:es.csic.iiia.planes.behaviors.AbstractBehaviorAgent.java
private void handle(Behavior b, Message m) { final Class<? extends Behavior> bClass = b.getClass(); final Class<? extends Message> mClass = m.getClass(); // Memoize the method Method method; if (cache.containsKey(bClass, mClass)) { method = (Method) cache.get(bClass, mClass); } else {//from w w w. ja va 2 s. c o m method = getMethod(bClass, mClass); if (method != null) { if (LOG.isLoggable(Level.FINEST)) { LOG.log(Level.FINEST, "Dispatching {0} to {1}", new Object[] { mClass.getSimpleName(), method.toGenericString() }); } } cache.put(bClass, mClass, method); } if (method == null) { return; } // Invoke it try { method.invoke(b, m); } catch (IllegalAccessException ex) { LOG.log(Level.SEVERE, null, ex); } catch (IllegalArgumentException ex) { LOG.log(Level.SEVERE, "Error invoking " + method.toGenericString() + " on " + b + " with argument " + m, ex); } catch (InvocationTargetException ex) { Throwable throwable = ex.getTargetException(); if (throwable instanceof Error) { throw (Error) throwable; } else if (throwable instanceof RuntimeException) { throw (RuntimeException) throwable; } LOG.log(Level.SEVERE, null, throwable); } }
From source file:org.xwiki.filter.xml.internal.serializer.DefaultXMLSerializer.java
@Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { Object result = null;/*w ww.j a va 2s .com*/ if (method.getName().startsWith("begin")) { beginEvent(method.getName(), args); } else if (method.getName().startsWith("end")) { endEvent(); } else if (method.getName().startsWith("on")) { onEvent(method.getName(), args); } else { throw new NoSuchMethodException(method.toGenericString()); } return result; }