List of usage examples for java.lang.reflect Method getExceptionTypes
@Override
public Class<?>[] getExceptionTypes()
From source file:org.apache.camel.component.bean.CamelInvocationHandler.java
/** * Tries to find the best suited exception to throw. * <p/>/*from w w w . ja v a 2 s.com*/ * It looks in the exception hierarchy from the caused exception and matches this against the declared exceptions * being thrown on the method. * * @param cause the caused exception * @param method the method * @return the exception to throw, or <tt>null</tt> if not possible to find a suitable exception */ protected Throwable findSuitableException(Throwable cause, Method method) { if (method.getExceptionTypes() == null || method.getExceptionTypes().length == 0) { return null; } // see if there is any exception which matches the declared exception on the method for (Class<?> type : method.getExceptionTypes()) { Object fault = ObjectHelper.getException(type, cause); if (fault != null) { return Throwable.class.cast(fault); } } return null; }
From source file:org.apache.struts2.interceptor.validation.AnnotationValidationInterceptor.java
protected String doIntercept(ActionInvocation invocation) throws Exception { Object action = invocation.getAction(); if (action != null) { Method method = getActionMethod(action.getClass(), invocation.getProxy().getMethod()); Collection<Method> annotatedMethods = AnnotationUtils.getAnnotatedMethods(action.getClass(), SkipValidation.class); if (annotatedMethods.contains(method)) return invocation.invoke(); //check if method overwites an annotated method Class clazz = action.getClass().getSuperclass(); while (clazz != null) { annotatedMethods = AnnotationUtils.getAnnotatedMethods(clazz, SkipValidation.class); if (annotatedMethods != null) { for (Method annotatedMethod : annotatedMethods) { if (annotatedMethod.getName().equals(method.getName()) && Arrays.equals(annotatedMethod.getParameterTypes(), method.getParameterTypes()) && Arrays.equals(annotatedMethod.getExceptionTypes(), method.getExceptionTypes())) return invocation.invoke(); }// ww w . j a va2 s.c o m } clazz = clazz.getSuperclass(); } } return super.doIntercept(invocation); }
From source file:org.assertj.assertions.generator.description.converter.ClassToClassDescriptionConverter.java
private List<TypeName> getExceptionTypeNames(final Method getter) { List<TypeName> exceptions = new ArrayList<TypeName>(); for (Class<?> exception : getter.getExceptionTypes()) { exceptions.add(new TypeName(exception)); }/*from w w w . j ava 2 s .co m*/ return exceptions; }
From source file:org.b3log.latke.servlet.handler.RouteHandler.java
/** * Adds the specified context handler meta * * @param contextHandlerMeta the specified context handler meta */// w w w. j a va2s . c o m public static void addContextHandlerMeta(final ContextHandlerMeta contextHandlerMeta) { final Method invokeHolder = contextHandlerMeta.getInvokeHolder(); final Class<?> returnType = invokeHolder.getReturnType(); final String methodName = invokeHolder.getDeclaringClass().getName() + "#" + invokeHolder.getName(); if (!void.class.equals(returnType)) { LOGGER.error("Handler method [" + methodName + "] must return void"); System.exit(-1); } final Class<?>[] exceptionTypes = invokeHolder.getExceptionTypes(); if (0 < exceptionTypes.length) { LOGGER.error("Handler method [" + methodName + "] can not throw exceptions"); System.exit(-1); } final Class<?>[] parameterTypes = invokeHolder.getParameterTypes(); if (1 != parameterTypes.length) { LOGGER.error("Handler method [" + methodName + "] must have one parameter with type [RequestContext]"); System.exit(-1); } final Class<?> parameterType = parameterTypes[0]; if (!RequestContext.class.equals(parameterType)) { LOGGER.error("Handler method [" + methodName + "] must have one parameter with type [RequestContext]"); System.exit(-1); } final HttpMethod[] httpMethods = contextHandlerMeta.getHttpMethods(); for (int i = 0; i < httpMethods.length; i++) { final String httpMethod = httpMethods[i].name(); final String[] uriTemplates = contextHandlerMeta.getUriTemplates(); for (int j = 0; j < uriTemplates.length; j++) { final String uriTemplate = uriTemplates[j]; final String key = httpMethod + "." + uriTemplate; final int segs = StringUtils.countMatches(uriTemplate, "/"); if (!StringUtils.contains(uriTemplate, "{")) { switch (segs) { case 1: ONE_SEG_CONCRETE_CTX_HANDLER_METAS.put(key, contextHandlerMeta); break; case 2: TWO_SEG_CONCRETE_CTX_HANDLER_METAS.put(key, contextHandlerMeta); break; case 3: THREE_SEG_CONCRETE_CTX_HANDLER_METAS.put(key, contextHandlerMeta); break; default: FOUR_MORE_SEG_CONCRETE_CTX_HANDLER_METAS.put(key, contextHandlerMeta); } } else { // URI templates contain path vars switch (segs) { case 1: switch (httpMethod) { case "GET": ONE_SEG_GET_VAR_CTX_HANDLER_METAS.put(uriTemplate, contextHandlerMeta); break; case "POST": ONE_SEG_POST_VAR_CTX_HANDLER_METAS.put(uriTemplate, contextHandlerMeta); break; case "PUT": ONE_SEG_PUT_VAR_CTX_HANDLER_METAS.put(uriTemplate, contextHandlerMeta); break; case "DELETE": ONE_SEG_DELETE_VAR_CTX_HANDLER_METAS.put(uriTemplate, contextHandlerMeta); break; default: ONE_SEG_OTHER_METHOD_VAR_CTX_HANDLER_METAS.put(uriTemplate, contextHandlerMeta); } break; case 2: switch (httpMethod) { case "GET": TWO_SEG_GET_VAR_CTX_HANDLER_METAS.put(uriTemplate, contextHandlerMeta); break; case "POST": TWO_SEG_POST_VAR_CTX_HANDLER_METAS.put(uriTemplate, contextHandlerMeta); break; case "PUT": TWO_SEG_PUT_VAR_CTX_HANDLER_METAS.put(uriTemplate, contextHandlerMeta); break; case "DELETE": TWO_SEG_DELETE_VAR_CTX_HANDLER_METAS.put(uriTemplate, contextHandlerMeta); break; default: TWO_SEG_OTHER_METHOD_VAR_CTX_HANDLER_METAS.put(uriTemplate, contextHandlerMeta); } break; case 3: switch (httpMethod) { case "GET": THREE_SEG_GET_VAR_CTX_HANDLER_METAS.put(uriTemplate, contextHandlerMeta); break; case "POST": THREE_SEG_POST_VAR_CTX_HANDLER_METAS.put(uriTemplate, contextHandlerMeta); break; case "PUT": THREE_SEG_PUT_VAR_CTX_HANDLER_METAS.put(uriTemplate, contextHandlerMeta); break; case "DELETE": THREE_SEG_DELETE_VAR_CTX_HANDLER_METAS.put(uriTemplate, contextHandlerMeta); break; default: THREE_SEG_OTHER_METHOD_VAR_CTX_HANDLER_METAS.put(uriTemplate, contextHandlerMeta); } break; default: switch (httpMethod) { case "GET": FOUR_MORE_SEG_GET_VAR_CTX_HANDLER_METAS.put(uriTemplate, contextHandlerMeta); break; case "POST": FOUR_MORE_SEG_POST_VAR_CTX_HANDLER_METAS.put(uriTemplate, contextHandlerMeta); break; case "PUT": FOUR_MORE_SEG_PUT_VAR_CTX_HANDLER_METAS.put(uriTemplate, contextHandlerMeta); break; case "DELETE": FOUR_MORE_SEG_DELETE_VAR_CTX_HANDLER_METAS.put(uriTemplate, contextHandlerMeta); break; default: FOUR_MORE_SEG_OTHER_METHOD_VAR_CTX_HANDLER_METAS.put(uriTemplate, contextHandlerMeta); } } } } } LOGGER.log(Level.DEBUG, "Added a processor method [" + methodName + "]"); }
From source file:org.codehaus.enunciate.modules.rest.RESTOperation.java
/** * Construct a REST operation./*from www . jav a 2 s.c om*/ * * @param resource The resource for this operation. * @param contentType The content type of the operation. * @param verb The verb for the operation. * @param method The method. * @param parameterNames The parameter names. */ protected RESTOperation(RESTResource resource, String contentType, VerbType verb, Method method, String[] parameterNames) { this.resource = resource; this.verb = verb; this.method = method; this.contentType = contentType; int properNounIndex = -1; Class properNoun = null; Boolean properNounOptional = null; int nounValueIndex = -1; Class nounValue = null; Boolean nounValueOptional = Boolean.FALSE; int contentTypeParameterIndex = -1; adjectiveTypes = new HashMap<String, Class>(); adjectiveIndices = new HashMap<String, Integer>(); adjectivesOptional = new HashMap<String, Boolean>(); complexAdjectives = new ArrayList<String>(); contextParameterTypes = new HashMap<String, Class>(); contextParameterIndices = new HashMap<String, Integer>(); Class[] parameterTypes = method.getParameterTypes(); HashSet<Class> contextClasses = new HashSet<Class>(); for (int i = 0; i < parameterTypes.length; i++) { Class parameterType = Collection.class.isAssignableFrom(parameterTypes[i]) ? getCollectionTypeAsArrayType(method, i) : parameterTypes[i]; boolean isAdjective = true; String adjectiveName = "arg" + i; if ((parameterNames != null) && (parameterNames.length > i) && (parameterNames[i] != null)) { adjectiveName = parameterNames[i]; } boolean adjectiveOptional = !parameterType.isPrimitive(); boolean adjectiveComplex = false; Annotation[] parameterAnnotations = method.getParameterAnnotations()[i]; for (Annotation annotation : parameterAnnotations) { if (annotation instanceof ProperNoun) { if (parameterType.isArray()) { throw new IllegalStateException( "Proper nouns must be simple types, found an array or collection for parameter " + i + " of method " + method.getDeclaringClass().getName() + "." + method.getName() + "."); } else if (properNoun == null) { ProperNoun properNounInfo = (ProperNoun) annotation; if (properNounInfo.optional()) { if (parameterType.isPrimitive()) { throw new IllegalStateException( "An optional proper noun cannot be a primitive type for method " + method.getDeclaringClass().getName() + "." + method.getName() + "."); } properNounOptional = true; } if (!properNounInfo.converter().equals(ProperNoun.DEFAULT.class)) { try { ConvertUtils.register((Converter) properNounInfo.converter().newInstance(), parameterType); } catch (ClassCastException e) { throw new IllegalArgumentException("Illegal converter class for method " + method.getDeclaringClass().getName() + "." + method.getName() + ". Must be an instance of org.apache.commons.beanutils.Converter."); } catch (Exception e) { throw new IllegalArgumentException("Unable to instantiate converter class " + properNounInfo.converter().getName() + " on method " + method.getDeclaringClass().getName() + "." + method.getName() + ".", e); } } properNoun = parameterType; properNounIndex = i; isAdjective = false; break; } else { throw new IllegalStateException("There are two proper nouns for method " + method.getDeclaringClass().getName() + "." + method.getName() + "."); } } else if (annotation instanceof NounValue) { if ((!parameterType.isAnnotationPresent(XmlRootElement.class)) && (!parameterType.equals(DataHandler.class)) && (!(parameterType.isArray() && parameterType.getComponentType().equals(DataHandler.class)))) { LOG.warn( "Enunciate doesn't support unmarshalling objects of type " + parameterType.getName() + ". Unless a custom content type handler is provided, this operation (" + method.getDeclaringClass() + "." + method.getName() + ") will fail."); } if (nounValue == null) { if (((NounValue) annotation).optional()) { if (parameterType.isPrimitive()) { throw new IllegalStateException( "An optional noun value cannot be a primitive type for method " + method.getDeclaringClass().getName() + "." + method.getName() + "."); } nounValueOptional = true; } nounValue = parameterType; nounValueIndex = i; isAdjective = false; break; } else { throw new IllegalStateException("There are two proper nouns for method " + method.getDeclaringClass().getName() + "." + method.getName() + "."); } } else if (annotation instanceof ContextParameter) { ContextParameter contextParameterInfo = (ContextParameter) annotation; String contextParameterName = contextParameterInfo.value(); if (!contextParameterInfo.converter().equals(ContextParameter.DEFAULT.class)) { try { ConvertUtils.register((Converter) contextParameterInfo.converter().newInstance(), parameterType); } catch (ClassCastException e) { throw new IllegalArgumentException("Illegal converter class for method " + method.getDeclaringClass().getName() + "." + method.getName() + ". Must be an instance of org.apache.commons.beanutils.Converter."); } catch (Exception e) { throw new IllegalArgumentException( "Unable to instantiate converter class " + contextParameterInfo.converter().getName() + " on method " + method.getDeclaringClass().getName() + "." + method.getName() + ".", e); } } contextParameterTypes.put(contextParameterName, parameterType); contextParameterIndices.put(contextParameterName, i); isAdjective = false; break; } else if (annotation instanceof ContentTypeParameter) { contentTypeParameterIndex = i; isAdjective = false; break; } else if (annotation instanceof Adjective) { Adjective adjectiveInfo = (Adjective) annotation; adjectiveOptional = adjectiveInfo.optional(); if (adjectiveOptional && parameterType.isPrimitive()) { throw new IllegalStateException( "An optional adjective cannot be a primitive type for method " + method.getDeclaringClass().getName() + "." + method.getName() + "."); } if (!"##default".equals(adjectiveInfo.name())) { adjectiveName = adjectiveInfo.name(); } adjectiveComplex = adjectiveInfo.complex(); if (!adjectiveInfo.converter().equals(Adjective.DEFAULT.class)) { try { ConvertUtils.register((Converter) adjectiveInfo.converter().newInstance(), parameterType); } catch (ClassCastException e) { throw new IllegalArgumentException("Illegal converter class for method " + method.getDeclaringClass().getName() + "." + method.getName() + ". Must be an instance of org.apache.commons.beanutils.Converter."); } catch (Exception e) { throw new IllegalArgumentException("Unable to instantiate converter class " + adjectiveInfo.converter().getName() + " on method " + method.getDeclaringClass().getName() + "." + method.getName() + ".", e); } } break; } } if (isAdjective) { this.adjectiveTypes.put(adjectiveName, parameterType); this.adjectiveIndices.put(adjectiveName, i); this.adjectivesOptional.put(adjectiveName, adjectiveOptional); if (adjectiveComplex) { this.complexAdjectives.add(adjectiveName); } } if (parameterType.isArray()) { contextClasses.add(parameterType.getComponentType()); } else { contextClasses.add(parameterType); } } Class returnType = null; if (!Void.TYPE.equals(method.getReturnType())) { returnType = method.getReturnType(); if (!returnType.isAnnotationPresent(XmlRootElement.class) && (!DataHandler.class.isAssignableFrom(returnType))) { LOG.warn("Enunciate doesn't support marshalling objects of type " + returnType.getName() + ". Unless a custom content type handler is provided, this operation (" + method.getDeclaringClass() + "." + method.getName() + ") will fail."); } contextClasses.add(returnType); } for (Class exceptionClass : method.getExceptionTypes()) { for (Method exceptionMethod : exceptionClass.getMethods()) { if ((exceptionMethod.isAnnotationPresent(RESTErrorBody.class)) && (exceptionMethod.getReturnType() != Void.TYPE)) { //add the error body to the context classes. contextClasses.add(exceptionMethod.getReturnType()); } } } //now load any additional context classes as specified by @RESTSeeAlso if (method.isAnnotationPresent(RESTSeeAlso.class)) { contextClasses.addAll(Arrays.asList(method.getAnnotation(RESTSeeAlso.class).value())); } if (method.getDeclaringClass().isAnnotationPresent(RESTSeeAlso.class)) { contextClasses .addAll(Arrays.asList(method.getDeclaringClass().getAnnotation(RESTSeeAlso.class).value())); } if ((method.getDeclaringClass().getPackage() != null) && (method.getDeclaringClass().getPackage().isAnnotationPresent(RESTSeeAlso.class))) { contextClasses.addAll(Arrays .asList(method.getDeclaringClass().getPackage().getAnnotation(RESTSeeAlso.class).value())); } String jsonpParameter = null; JSONP jsonpInfo = method.getAnnotation(JSONP.class); if (jsonpInfo == null) { jsonpInfo = method.getDeclaringClass().getAnnotation(JSONP.class); if (jsonpInfo == null) { jsonpInfo = method.getDeclaringClass().getPackage().getAnnotation(JSONP.class); } } if (jsonpInfo != null) { jsonpParameter = jsonpInfo.paramName(); } String charset = "utf-8"; org.codehaus.enunciate.rest.annotations.ContentType contentTypeInfo = method .getAnnotation(org.codehaus.enunciate.rest.annotations.ContentType.class); if (contentTypeInfo == null) { contentTypeInfo = method.getDeclaringClass() .getAnnotation(org.codehaus.enunciate.rest.annotations.ContentType.class); if (contentTypeInfo == null) { contentTypeInfo = method.getDeclaringClass().getPackage() .getAnnotation(org.codehaus.enunciate.rest.annotations.ContentType.class); } } if (contentTypeInfo != null) { charset = contentTypeInfo.charset(); } String defaultNamespace = ""; if (method.getDeclaringClass().getPackage() != null && method.getDeclaringClass().getPackage().isAnnotationPresent(XmlSchema.class)) { defaultNamespace = method.getDeclaringClass().getPackage().getAnnotation(XmlSchema.class).namespace(); } this.properNounType = properNoun; this.properNounIndex = properNounIndex; this.properNounOptional = properNounOptional; this.nounValueType = nounValue; this.nounValueIndex = nounValueIndex; this.nounValueOptional = nounValueOptional; this.resultType = returnType; this.charset = charset; this.JSONPParameter = jsonpParameter; this.contextClasses = contextClasses; this.contentTypeParameterIndex = contentTypeParameterIndex; this.defaultNamespace = defaultNamespace; }
From source file:org.hyperic.hq.agent.server.monitor.AgentMonitorSimple.java
/** * Go through all the methods that we define to find ones which * match the signature we're looking for *//*w w w . jav a 2 s . c om*/ private void setupMethodMap() { Method[] methods; Class asClass = String[].class, aiClass = int[].class; int j; methods = this.getClass().getMethods(); for (int i = 0; i < methods.length; i++) { Method m = methods[i]; Class[] exceptions; Class retType; if (m.getName().startsWith("get") == false || m.getParameterTypes().length != 0) { continue; } exceptions = m.getExceptionTypes(); if (exceptions.length != 1 || exceptions[0].equals(AgentMonitorException.class) == false) { continue; } retType = m.getReturnType(); if (retType.equals(String.class) == false && retType.equals(Double.TYPE) == false && retType.equals(asClass) == false && retType.equals(aiClass) == false) { continue; } this.methodMap.put(m.getName().substring(3), m); } this.methodKeys = new String[this.methodMap.size()]; this.methodTypes = new int[this.methodKeys.length]; j = 0; for (Iterator i = this.methodMap.keySet().iterator(); i.hasNext(); j++) { String key = (String) i.next(); Method m = (Method) this.methodMap.get(key); Class retType = m.getReturnType(); int type; this.methodKeys[j] = key; if (retType.equals(String.class)) type = AgentMonitorValue.TYPE_STRING; else if (retType.equals(Double.TYPE)) type = AgentMonitorValue.TYPE_DOUBLE; else if (retType.equals(asClass)) type = AgentMonitorValue.TYPE_ASTRING; else if (retType.equals(aiClass)) type = AgentMonitorValue.TYPE_AINT; else throw new IllegalStateException("Should never get here"); this.methodTypes[j] = type; } }
From source file:org.jgentleframework.utils.ReflectUtils.java
/** * Determine whether the given method explicitly declares the given * exception or one of its superclasses, which means that an exception of * that type can be propagated as-is within a reflective invocation. * /*from w ww. j a v a 2 s . c om*/ * @param method * <the declaring method * @param exceptionType * the exception to throw * @return <code>true</code> if the exception can be thrown as-is; * <code>false</code> if it needs to be wrapped */ @SuppressWarnings("unchecked") public static boolean isDeclaredException(Method method, Class<? extends Throwable> exceptionType) { Assertor.notNull(method, "Method [" + method + "] must not be null."); Class<? extends Throwable>[] declaredExceptions = (Class<? extends Throwable>[]) method.getExceptionTypes(); for (int i = 0; i < declaredExceptions.length; i++) { Class<? extends Throwable> declaredException = declaredExceptions[i]; if (declaredException.isAssignableFrom(exceptionType)) { return true; } } return false; }
From source file:org.mule.component.BindingInvocationHandler.java
/** * Return the causing exception instead of the general "container" exception (typically * UndeclaredThrowableException) if the cause is known and the type matches one of the * exceptions declared in the given method's "throws" clause. */// www . j a v a 2s . c o m private Throwable findDeclaredMethodException(Method method, Throwable throwable) throws Throwable { Throwable cause = throwable.getCause(); if (cause != null) { // Try to find a matching exception type from the method's "throws" clause, and if so // return that exception. Class<?>[] exceptions = method.getExceptionTypes(); for (int i = 0; i < exceptions.length; i++) { if (cause.getClass().equals(exceptions[i])) { return cause; } } } return throwable; }
From source file:org.pircbotx.hooks.ListenerAdapterTest.java
@Test(dependsOnMethods = "eventImplementTest", dataProviderClass = TestUtils.class, dataProvider = "eventAllDataProvider", description = "Verify all methods in ListenerAdapter throw an exception") public void throwsExceptionTest(Class eventClass) throws NoSuchMethodException { String methodName = "on" + StringUtils.removeEnd(StringUtils.capitalize(eventClass.getSimpleName()), "Event"); Method eventMethod = ListenerAdapter.class.getDeclaredMethod(methodName, eventClass); Class<?>[] exceptions = eventMethod.getExceptionTypes(); assertEquals(exceptions.length, 1,//from w w w . j a va 2 s . c o m "Method " + eventMethod + " in ListenerManager doesn't throw an exception or thows too many"); assertEquals(exceptions[0], Exception.class, "Method " + eventMethod + " in ListenerManager doesn't throw the right exception"); }
From source file:org.power.commons.lang.util.ClassUtils.java
/** * ??method??/*from w w w . j a v a2 s . c o m*/ */ public static String getSimpleMethodSignature(Method method, boolean withModifiers, boolean withReturnType, boolean withClassName, boolean withExceptionType) { if (method == null) { return null; } StringBuilder buf = new StringBuilder(); if (withModifiers) { buf.append(Modifier.toString(method.getModifiers())).append(' '); } if (withReturnType) { buf.append(getSimpleClassName(method.getReturnType())).append(' '); } if (withClassName) { buf.append(getSimpleClassName(method.getDeclaringClass())).append('.'); } buf.append(method.getName()).append('('); Class<?>[] paramTypes = method.getParameterTypes(); for (int i = 0; i < paramTypes.length; i++) { Class<?> paramType = paramTypes[i]; buf.append(getSimpleClassName(paramType)); if (i < paramTypes.length - 1) { buf.append(", "); } } buf.append(')'); if (withExceptionType) { Class<?>[] exceptionTypes = method.getExceptionTypes(); if (ArrayUtils.isNotEmpty(exceptionTypes)) { buf.append(" throws "); for (int i = 0; i < exceptionTypes.length; i++) { Class<?> exceptionType = exceptionTypes[i]; buf.append(getSimpleClassName(exceptionType)); if (i < exceptionTypes.length - 1) { buf.append(", "); } } } } return buf.toString(); }