Example usage for java.lang.reflect Method getExceptionTypes

List of usage examples for java.lang.reflect Method getExceptionTypes

Introduction

In this page you can find the example usage for java.lang.reflect Method getExceptionTypes.

Prototype

@Override
public Class<?>[] getExceptionTypes() 

Source Link

Usage

From source file:Mopex.java

/**
 * Returns a String that is formatted as a Java method declaration having
 * the same header as the specified method but with the code parameter
 * substituted for the method body.//  w  ww . j  a v a  2 s. c o  m
 * 
 * @return String
 * @param m
 *            java.lang.Method
 * @param code
 *            String
 */
//start extract createReplacementMethod
public static String createReplacementMethod(Method m, String code) {
    Class[] pta = m.getParameterTypes();
    String fpl = formalParametersToString(pta);
    Class[] eTypes = m.getExceptionTypes();
    String result = m.getName() + "(" + fpl + ")\n";
    if (eTypes.length != 0)
        result += "    throws " + classArrayToString(eTypes) + "\n";
    result += "{\n" + code + "}\n";
    return result;
}

From source file:com.liferay.cli.support.util.ReflectionUtils.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 w  w. ja v  a  2  s. co m
 * @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
 */
public static boolean declaresException(final Method method, final Class<?> exceptionType) {
    Validate.notNull(method, "Method must not be null");
    final Class<?>[] declaredExceptions = method.getExceptionTypes();
    for (final Class<?> declaredException : declaredExceptions) {
        if (declaredException.isAssignableFrom(exceptionType)) {
            return true;
        }
    }
    return false;
}

From source file:br.com.lucasisrael.regra.reflections.TratamentoReflections.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.
 * @param method the declaring method/*from  w w w .  j  ava  2 s  .  c  o m*/
 * @param exceptionType the exception to throw
 * @return {@code true} if the exception can be thrown as-is;
 * {@code false} if it needs to be wrapped
 */
public static boolean declaresException(Method method, Class<?> exceptionType) {
    Assert.notNull(method, "Method must not be null");
    Class<?>[] declaredExceptions = method.getExceptionTypes();
    for (Class<?> declaredException : declaredExceptions) {
        if (declaredException.isAssignableFrom(exceptionType)) {
            return true;
        }
    }
    return false;
}

From source file:Mopex.java

/**
 * Returns a string for a cooperative override of the method m. That is, The
 * string has the same return type and signature as m but the body has a
 * super call that is sandwiched between the strings code1 and code2.
 * /*w w w  . j  a  v a 2s.  c  om*/
 * @return String
 * @param m
 *            java.lang.Method
 * @param code1
 *            String
 * @param code2
 *            String
 */
//start extract createCooperativeWrapper
public static String createCooperativeWrapper(Method m, String code1, String code2) {
    Class[] pta = m.getParameterTypes();
    Class retType = m.getReturnType();
    String fpl = formalParametersToString(pta);
    String apl = actualParametersToString(pta);
    Class[] eTypes = m.getExceptionTypes();
    String result = retType.getName() + " " + m.getName() + "(" + fpl + ")\n";
    if (eTypes.length != 0)
        result += "    throws " + classArrayToString(eTypes) + "\n";
    result += "{\n" + code1 + "    ";
    if (retType != void.class)
        result += retType.getName() + " cooperativeReturnValue = ";
    result += "super." + m.getName() + "(" + apl + ");\n";
    result += code2;
    if (retType != void.class)
        result += "    return cooperativeReturnValue;\n";
    result += "}\n";
    return result;
}

From source file:com.bstek.dorado.core.el.DefaultExpressionHandler.java

protected synchronized static Object createDoradoExpressionUtilsBean(Map<String, Method> utilMethods)
        throws Exception {
    if (doradoExpressionUtilsBean == null) {
        ClassPool pool = ClassPool.getDefault();
        CtClass ctClass = null;/* w w  w. j av a 2  s . c  o m*/
        try {
            ctClass = pool.get(DORADO_EXPRESSION_UTILS_TYPE);
        } catch (Exception e) {
            // do nothing
        }
        if (ctClass == null) {
            ctClass = pool.makeClass(DORADO_EXPRESSION_UTILS_TYPE);
        }
        for (Map.Entry<String, Method> entry : utilMethods.entrySet()) {
            String name = entry.getKey();
            Method method = entry.getValue();
            int methodIndex = ArrayUtils.indexOf(method.getDeclaringClass().getMethods(), method);

            StringBuffer buf = new StringBuffer();
            StringBuffer args = new StringBuffer();
            buf.append("public ").append("Object").append(' ').append(name).append('(');
            Class<?>[] parameterTypes = method.getParameterTypes();
            for (int i = 0; i < parameterTypes.length; i++) {
                if (i > 0) {
                    buf.append(',');
                    args.append(',');
                }
                buf.append("Object").append(' ').append("p" + i);
                args.append("p" + i);
            }
            buf.append(")");
            if (method.getExceptionTypes().length > 0) {
                buf.append(" throws ");
                int i = 0;
                for (Class<?> exceptionType : method.getExceptionTypes()) {
                    if (i > 0)
                        buf.append(',');
                    buf.append(exceptionType.getName());
                    i++;
                }
            }
            buf.append("{\n").append("return Class.forName(\"" + method.getDeclaringClass().getName())
                    .append("\").getMethods()[").append(methodIndex).append("].invoke(null, new Object[]{")
                    .append(args).append("});").append("\n}");
            CtMethod delegator = CtNewMethod.make(buf.toString(), ctClass);
            delegator.setName(name);
            ctClass.addMethod(delegator);
        }
        Class<?> cl = ctClass.toClass();
        doradoExpressionUtilsBean = cl.newInstance();
    }
    return doradoExpressionUtilsBean;
}

From source file:de.bund.bva.pliscommon.serviceapi.core.serviceimpl.ReflectiveExceptionMappingSource.java

/**
 * {@inheritDoc}/*from  w ww  .j a v a2  s  .  c o m*/
 */
public Class<? extends PlisTechnicalToException> getGenericTechnicalToException(Method remoteBeanMethod) {
    Class<? extends PlisTechnicalToException> genericTechnicalToException = null;
    for (Class<?> toExceptionClass : remoteBeanMethod.getExceptionTypes()) {
        if (PlisTechnicalToException.class.isAssignableFrom(toExceptionClass)) {
            if (genericTechnicalToException != null) {
                throw new IllegalStateException("Mehr als eine Technical-TO-Exception in Serviceoperation "
                        + getMethodSignatureString(remoteBeanMethod));
            }
            @SuppressWarnings("unchecked")
            Class<? extends PlisTechnicalToException> castToExceptionClass = (Class<? extends PlisTechnicalToException>) toExceptionClass;
            genericTechnicalToException = castToExceptionClass;
        }
    }

    if (genericTechnicalToException != null) {
        return genericTechnicalToException;
    }

    throw new IllegalStateException(
            "Keine Technical-TO-Exception in Serviceoperation " + getMethodSignatureString(remoteBeanMethod));
}

From source file:org.bytesoft.bytetcc.supports.dubbo.validator.ReferenceConfigValidator.java

public void validate() throws BeansException {
    MutablePropertyValues mpv = this.beanDefinition.getPropertyValues();
    PropertyValue retries = mpv.getPropertyValue("retries");
    PropertyValue loadbalance = mpv.getPropertyValue("loadbalance");
    PropertyValue cluster = mpv.getPropertyValue("cluster");
    PropertyValue filter = mpv.getPropertyValue("filter");

    if (retries == null || retries.getValue() == null || "0".equals(retries.getValue()) == false) {
        throw new FatalBeanException(
                String.format("The value of attr 'retries'(beanId= %s) should be '0'.", this.beanName));
    } else if (loadbalance == null || loadbalance.getValue() == null
            || "compensable".equals(loadbalance.getValue()) == false) {
        throw new FatalBeanException(String
                .format("The value of attr 'loadbalance'(beanId= %s) should be 'compensable'.", this.beanName));
    } else if (cluster == null || cluster.getValue() == null
            || "failfast".equals(cluster.getValue()) == false) {
        throw new FatalBeanException(String
                .format("The value of attribute 'cluster' (beanId= %s) must be 'failfast'.", this.beanName));
    } else if (filter == null || filter.getValue() == null
            || "compensable".equals(filter.getValue()) == false) {
        throw new FatalBeanException(String
                .format("The value of attr 'filter'(beanId= %s) should be 'compensable'.", this.beanName));
    }//from   www .j ava  2 s .  c o m

    PropertyValue pv = mpv.getPropertyValue("interface");
    String clazzName = String.valueOf(pv.getValue());
    ClassLoader cl = Thread.currentThread().getContextClassLoader();

    Class<?> clazz = null;
    try {
        clazz = cl.loadClass(clazzName);
    } catch (Exception ex) {
        throw new FatalBeanException(String.format("Cannot load class %s.", clazzName));
    }

    Method[] methodArray = clazz.getMethods();
    for (int i = 0; i < methodArray.length; i++) {
        Method method = methodArray[i];
        boolean declared = false;
        Class<?>[] exceptionTypeArray = method.getExceptionTypes();
        for (int j = 0; j < exceptionTypeArray.length; j++) {
            Class<?> exceptionType = exceptionTypeArray[j];
            if (RemotingException.class.isAssignableFrom(exceptionType)) {
                declared = true;
                break;
            }
        }

        if (declared == false) {
            // throw new FatalBeanException(String.format(
            // "The remote call method(%s) must be declared to throw a remote exception:
            // org.bytesoft.compensable.RemotingException!",
            // method));
            logger.warn("The remote call method({}) should be declared to throw a remote exception: {}!",
                    method, RemotingException.class.getName());
        }

    }

}

From source file:com.strandls.alchemy.webservices.common.json.ExceptionObjectMapperModule.java

/**
 * Binding for throwable exception mapper.
 *
 * @param mapper/*from  w w w .  j  av a2  s.c o  m*/
 * @return
 */
@Provides
@Singleton
@ThrowableObjectMapper
@Inject
public ObjectMapper getExceptionObjectMapper(final ObjectMapper mapper,
        final RestInterfaceAnalyzer restInterfaceAnalyzer, final JavaTypeQueryHandler typeQueryHandler) {
    // can't copy owing to bug -
    // https://github.com/FasterXML/jackson-databind/issues/245
    final ObjectMapper exceptionMapper = mapper;
    exceptionMapper.registerModule(new SimpleModule() {
        /**
         * The serial version id.
         */
        private static final long serialVersionUID = 1L;

        /*
         * (non-Javadoc)
         * @see
         * com.fasterxml.jackson.databind.module.SimpleModule#setupModule
         * (com.fasterxml.jackson.databind.Module.SetupContext)
         */
        @Override
        public void setupModule(final SetupContext context) {
            // find exceptions thrown by webservices
            final Set<Class<?>> serviceClasses = typeQueryHandler.getTypesAnnotatedWith(ALCHEMY_SERVICE_PACKAGE,
                    Path.class);
            final Set<Class<?>> exceptionsUsed = new HashSet<Class<?>>();
            for (final Class<?> serviceClass : serviceClasses) {
                // get hold of all rest methods and hence exception
                try {
                    final Set<Method> restMethods = restInterfaceAnalyzer.analyze(serviceClass)
                            .getMethodMetaData().keySet();
                    for (final Method method : restMethods) {
                        for (final Class<?> exceptionClass : method.getExceptionTypes()) {
                            exceptionsUsed.add(exceptionClass);
                        }
                    }
                } catch (final NotRestInterfaceException e) {
                    log.error("Error geting exception classes for methods from {}", serviceClass);
                    throw new RuntimeException(e);
                }
            }

            // add the mixin to all jaxrs classes as well.
            exceptionsUsed
                    .addAll(typeQueryHandler.getSubTypesOf(JAVAX_WS_RS_PACKAGE, WebApplicationException.class));

            for (final Class<?> exceptionClass : exceptionsUsed) {
                // add a mixin to prevent server stack trace from showing up
                // to the client.
                log.debug("Applied mixin mask to {}", exceptionClass);
                context.setMixInAnnotations(exceptionClass, ThrowableMaskMixin.class);
            }

        }
    });
    exceptionMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    return exceptionMapper;
}

From source file:co.paralleluniverse.springframework.web.method.support.FiberInvocableHandlerMethod.java

/**
 * @return `true` if the method is not annotated with `@Suspendable` and it doesn't throw `SuspendExecution` nor it is instrumented in any other way.
 */// w w w  .  j a v a  2  s.  c o  m
private boolean isSpringTraditionalThreadBlockingControllerMethod() {
    final Method m = getMethod();
    return m.getAnnotation(Suspendable.class) == null
            && !Arrays.asList(m.getExceptionTypes()).contains(SuspendExecution.class)
            && !SuspendableHelper.isInstrumented(m);
}

From source file:de.bund.bva.pliscommon.serviceapi.core.serviceimpl.ReflectiveExceptionMappingSource.java

/**
 * {@inheritDoc}// ww  w  . j a  va  2 s  . co  m
 */
public Class<? extends PlisToException> getToExceptionClass(Method remoteBeanMethod,
        Class<? extends PlisException> exceptionClass) {

    String coreExceptionName = StringUtils.removeEnd(exceptionClass.getSimpleName(), "Exception");

    for (Class<?> toExceptionClass : remoteBeanMethod.getExceptionTypes()) {
        if (PlisToException.class.isAssignableFrom(toExceptionClass)) {
            String toExceptionName = StringUtils.removeEnd(toExceptionClass.getSimpleName(), "ToException");
            if (coreExceptionName.equals(toExceptionName)) {
                @SuppressWarnings("unchecked")
                Class<? extends PlisToException> castToExceptionClass = (Class<? extends PlisToException>) toExceptionClass;
                return castToExceptionClass;
            }
        }
    }

    throw new IllegalStateException("Keine TO-Exception fr die AWK-Exception " + exceptionClass
            + " in Serviceoperation " + getMethodSignatureString(remoteBeanMethod));
}