Java Code Examples for java.lang.reflect.Method#getExceptionTypes()

The following examples show how to use java.lang.reflect.Method#getExceptionTypes() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ReflectionServiceFactoryBean.java    From cxf with Apache License 2.0 6 votes vote down vote up
protected void initializeFaults(final InterfaceInfo service,
                                final OperationInfo op, final Method method) {
    // Set up the fault messages
    final Class<?>[] exceptionClasses = method.getExceptionTypes();
    for (int i = 0; i < exceptionClasses.length; i++) {
        Class<?> exClazz = exceptionClasses[i];

        // Ignore XFireFaults because they don't need to be declared
        if (Fault.class.isAssignableFrom(exClazz)
            || exClazz.equals(RuntimeException.class) || exClazz.equals(Throwable.class)) {
            continue;
        }

        addFault(service, op, exClazz);
    }
}
 
Example 2
Source File: SpringExceptionHandlerReader.java    From swagger-maven-plugin with Apache License 2.0 6 votes vote down vote up
protected List<ResponseStatus> getResponseStatusesFromExceptions(Method method) {
    List<ResponseStatus> result = new LinkedList<ResponseStatus>();
    for (Class exceptionClass: method.getExceptionTypes()) {
        ResponseStatus responseStatus = exceptionMapping.get(exceptionClass);

        // fallback to exception own annotation
        if (null == responseStatus) {
            responseStatus = findMergedAnnotation(exceptionClass, ResponseStatus.class);
        }

        if (null != responseStatus) {
            result.add(responseStatus);
        }
    }
    return result;
}
 
Example 3
Source File: IDLTypesUtil.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Returns true if the method's throw clause conforms to the exception
 * restrictions for properties as defined in Section 1.3.4.3 of
 * Java2IDL spec.  This means that for all exceptions E declared on the
 * method, E isChecked => RemoteException.isAssignableFrom( E ).
 */
private boolean validPropertyExceptions(Method method)
{
    Class[] exceptions = method.getExceptionTypes();

    for(int eIndex = 0; eIndex < exceptions.length; eIndex++) {
        Class exception = exceptions[eIndex];

        if (isCheckedException(exception) && !isRemoteException(exception))
            return false ;
    }

    return true;
}
 
Example 4
Source File: ProxyGenerator.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Add another method to be proxied, either by creating a new
 * ProxyMethod object or augmenting an old one for a duplicate
 * method.
 *
 * "fromClass" indicates the proxy interface that the method was
 * found through, which may be different from (a subinterface of)
 * the method's "declaring class".  Note that the first Method
 * object passed for a given name and descriptor identifies the
 * Method object (and thus the declaring class) that will be
 * passed to the invocation handler's "invoke" method for a given
 * set of duplicate methods.
 */
private void addProxyMethod(Method m, Class<?> fromClass) {
    String name = m.getName();
    Class<?>[] parameterTypes = m.getParameterTypes();
    Class<?> returnType = m.getReturnType();
    Class<?>[] exceptionTypes = m.getExceptionTypes();

    String sig = name + getParameterDescriptors(parameterTypes);
    List<ProxyMethod> sigmethods = proxyMethods.get(sig);
    if (sigmethods != null) {
        for (ProxyMethod pm : sigmethods) {
            if (returnType == pm.returnType) {
                /*
                 * Found a match: reduce exception types to the
                 * greatest set of exceptions that can thrown
                 * compatibly with the throws clauses of both
                 * overridden methods.
                 */
                List<Class<?>> legalExceptions = new ArrayList<>();
                collectCompatibleTypes(
                    exceptionTypes, pm.exceptionTypes, legalExceptions);
                collectCompatibleTypes(
                    pm.exceptionTypes, exceptionTypes, legalExceptions);
                pm.exceptionTypes = new Class<?>[legalExceptions.size()];
                pm.exceptionTypes =
                    legalExceptions.toArray(pm.exceptionTypes);
                return;
            }
        }
    } else {
        sigmethods = new ArrayList<>(3);
        proxyMethods.put(sig, sigmethods);
    }
    sigmethods.add(new ProxyMethod(name, parameterTypes, returnType,
                                   exceptionTypes, fromClass));
}
 
Example 5
Source File: ProxyGenerator.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Add another method to be proxied, either by creating a new
 * ProxyMethod object or augmenting an old one for a duplicate
 * method.
 *
 * "fromClass" indicates the proxy interface that the method was
 * found through, which may be different from (a subinterface of)
 * the method's "declaring class".  Note that the first Method
 * object passed for a given name and descriptor identifies the
 * Method object (and thus the declaring class) that will be
 * passed to the invocation handler's "invoke" method for a given
 * set of duplicate methods.
 */
private void addProxyMethod(Method m, Class<?> fromClass) {
    String name = m.getName();
    Class<?>[] parameterTypes = m.getParameterTypes();
    Class<?> returnType = m.getReturnType();
    Class<?>[] exceptionTypes = m.getExceptionTypes();

    String sig = name + getParameterDescriptors(parameterTypes);
    List<ProxyMethod> sigmethods = proxyMethods.get(sig);
    if (sigmethods != null) {
        for (ProxyMethod pm : sigmethods) {
            if (returnType == pm.returnType) {
                /*
                 * Found a match: reduce exception types to the
                 * greatest set of exceptions that can thrown
                 * compatibly with the throws clauses of both
                 * overridden methods.
                 */
                List<Class<?>> legalExceptions = new ArrayList<>();
                collectCompatibleTypes(
                    exceptionTypes, pm.exceptionTypes, legalExceptions);
                collectCompatibleTypes(
                    pm.exceptionTypes, exceptionTypes, legalExceptions);
                pm.exceptionTypes = new Class<?>[legalExceptions.size()];
                pm.exceptionTypes =
                    legalExceptions.toArray(pm.exceptionTypes);
                return;
            }
        }
    } else {
        sigmethods = new ArrayList<>(3);
        proxyMethods.put(sig, sigmethods);
    }
    sigmethods.add(new ProxyMethod(name, parameterTypes, returnType,
                                   exceptionTypes, fromClass));
}
 
Example 6
Source File: VerifySignatures.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
/**
 * checks that a class implements a specific method.
 * @param derbyImplementation The Derby implementation class which is tested
 * @param ifaceMethod The method that should be implemented.
 */
private static void checkImplementationMethod(
        Class derbyImplementation, Method ifaceMethod)
    throws NoSuchMethodException
{
    
        assertFalse("Implementation class is interface",
                    derbyImplementation.isInterface());

        Method impMethod =
            derbyImplementation.getMethod(ifaceMethod.getName(),
                                          ifaceMethod.getParameterTypes());

        assertEquals("Incorrect return type",
                     ifaceMethod.getReturnType(),
                     impMethod.getReturnType());

        int modifiers = impMethod.getModifiers();
        assertTrue("Non-public method", Modifier.isPublic(modifiers));
        assertFalse("Abstract method", Modifier.isAbstract(modifiers));
        assertFalse("Static method", Modifier.isStatic(modifiers));

        Class[] declaredExceptions = ifaceMethod.getExceptionTypes();
        for (Class exception : impMethod.getExceptionTypes()) {
            if (RuntimeException.class.isAssignableFrom(exception)) {
                continue;
            }
            assertNotNull("Incompatible throws clause",
                          findCompatibleClass(exception,
                                              declaredExceptions));
        }
    }
 
Example 7
Source File: Util.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Verifies that the supplied method has at least one declared exception
 * type that is RemoteException or one of its superclasses.  If not,
 * then this method throws IllegalArgumentException.
 *
 * @throws IllegalArgumentException if m is an illegal remote method
 */
private static void checkMethod(Method m) {
    Class<?>[] ex = m.getExceptionTypes();
    for (int i = 0; i < ex.length; i++) {
        if (ex[i].isAssignableFrom(RemoteException.class))
            return;
    }
    throw new IllegalArgumentException(
        "illegal remote method encountered: " + m);
}
 
Example 8
Source File: Model.java    From yGuard with MIT License 5 votes vote down vote up
/**
 * convert java.lang.reflect.Method to MethodDescriptor
 *
 * @param m java Method
 * @return a MethodDescriptor with the same properties as Method <code>m</code>.
 */
private MethodDescriptor method2Descriptor( final Method m, final File sourceJar ) {

  final int access = m.getModifiers();
  final String desc = Type.getMethodDescriptor( m );
  final Class[] exceptionClasses = m.getExceptionTypes();
  final String[] exceptions = new String[ exceptionClasses.length ];
  for ( int i = 0; i < exceptionClasses.length; i++ ) {
    exceptions[ i ] = exceptionClasses[ i ].getName();
  }

  return new MethodDescriptor( m.getName(), access, desc, exceptions, sourceJar );
}
 
Example 9
Source File: ReflectiveCallNotNullImplementor.java    From Quicksql with MIT License 5 votes vote down vote up
private boolean containsCheckedException(Method method) {
  Class[] exceptions = method.getExceptionTypes();
  if (exceptions == null || exceptions.length == 0) {
    return false;
  }
  for (Class clazz : exceptions) {
    if (!RuntimeException.class.isAssignableFrom(clazz)) {
      return true;
    }
  }
  return false;
}
 
Example 10
Source File: AbstractEndpointHandler.java    From tomee with Apache License 2.0 5 votes vote down vote up
private boolean isValidException(final Method method, final Throwable throwable) {
    if (throwable instanceof RuntimeException || throwable instanceof Error) {
        return true;
    }

    final Class<?>[] exceptionTypes = method.getExceptionTypes();
    for (final Class<?> exceptionType : exceptionTypes) {
        if (exceptionType.isInstance(throwable)) {
            return true;
        }
    }
    return false;
}
 
Example 11
Source File: DynamicMethodMarshallerImpl.java    From jdk1.8-source-analysis with Apache License 2.0 5 votes vote down vote up
private static boolean throwsRemote( Method method )
{
    Class[] exceptionTypes = method.getExceptionTypes() ;

    // Check that some exceptionType is a subclass of RemoteException
    for (int ctr=0; ctr<exceptionTypes.length; ctr++) {
        Class exceptionType = exceptionTypes[ctr] ;
        if (java.rmi.RemoteException.class.isAssignableFrom( exceptionType ))
            return true ;
    }

    return false ;
}
 
Example 12
Source File: IDLTypesUtil.java    From jdk1.8-source-analysis with Apache License 2.0 5 votes vote down vote up
/**
 * Returns true if the method's throw clause conforms to the exception
 * restrictions for properties as defined in Section 1.3.4.3 of
 * Java2IDL spec.  This means that for all exceptions E declared on the
 * method, E isChecked => RemoteException.isAssignableFrom( E ).
 */
private boolean validPropertyExceptions(Method method)
{
    Class[] exceptions = method.getExceptionTypes();

    for(int eIndex = 0; eIndex < exceptions.length; eIndex++) {
        Class exception = exceptions[eIndex];

        if (isCheckedException(exception) && !isRemoteException(exception))
            return false ;
    }

    return true;
}
 
Example 13
Source File: RpcReaderExtension.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
private String outputMethod(Method method) {
    try {
        Class<?>[] types = method.getParameterTypes();
        Class<?>[] exceptionTypes = method.getExceptionTypes();
        StringBuilder sb = new StringBuilder();

        sb.append(method.getReturnType().getSimpleName()).append(" ").append(method.getName());

        sb.append('(');
        for (int j = 0; j < types.length; j++) {
            sb.append(types[j].getName());
            if (j < (types.length - 1)) {
                sb.append(",");
            }
        }
        sb.append(')');
        if (exceptionTypes.length > 0) {
            sb.append(" throws ");
            for (int j = 0; j < exceptionTypes.length; j++) {
                sb.append(exceptionTypes[j].getSimpleName());
                if (j < (exceptionTypes.length - 1)) {
                    sb.append(",");
                }
            }
        }
        return sb.toString();
    } catch (Exception e) {
        return "<" + e + ">";
    }

}
 
Example 14
Source File: S3RateLimiter.java    From emodb with Apache License 2.0 5 votes vote down vote up
private Throwable asDeclaredThrowable(Throwable t, Method method) throws Throwable {
    // Do our best to re-throw the exception as it is declared
    for (Class<?> declaredException : method.getExceptionTypes()) {
        // noinspection unchecked
        Throwables.propagateIfInstanceOf(t, (Class<? extends Throwable>) declaredException);
    }
    throw Throwables.propagate(t);
}
 
Example 15
Source File: ClientProxyImpl.java    From cxf with Apache License 2.0 4 votes vote down vote up
protected void checkResponse(Method m, Response r, Message inMessage) throws Throwable {
    Throwable t = null;
    int status = r.getStatus();

    if (status >= 300) {
        Class<?>[] exTypes = m.getExceptionTypes();
        if (exTypes.length == 0) {
            exTypes = new Class<?>[]{WebApplicationException.class};
        }
        for (Class<?> exType : exTypes) {
            ResponseExceptionMapper<?> mapper = findExceptionMapper(inMessage, exType);
            if (mapper != null) {
                t = mapper.fromResponse(r);
                if (t != null) {
                    throw t;
                }
            }
        }

        if ((t == null) && (m.getReturnType() == Response.class) && (m.getExceptionTypes().length == 0)) {
            return;
        }

        t = convertToWebApplicationException(r);

        if (inMessage.getExchange().get(Message.RESPONSE_CODE) == null) {
            throw t;
        }

        Endpoint ep = inMessage.getExchange().getEndpoint();
        inMessage.getExchange().put(InterceptorProvider.class, getConfiguration());
        inMessage.setContent(Exception.class, new Fault(t));
        inMessage.getInterceptorChain().abort();
        if (ep.getInFaultObserver() != null) {
            ep.getInFaultObserver().onMessage(inMessage);
        }

        throw t;

    }
}
 
Example 16
Source File: JClassDependency.java    From baratine with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Calculates a MD5 digest of the class.
 */
public String getDigest()
{
  try {
    if (_className == null || "".equals(_className))
      return "";
    
    DynamicClassLoader loader
      = (DynamicClassLoader) Thread.currentThread().getContextClassLoader();

    ClassLoader tmpLoader = loader.getNewTempClassLoader();
    
    Class cl = Class.forName(_className, false, tmpLoader);
    
    if (cl == null)
      return "";

    MessageDigest digest = MessageDigest.getInstance("MD5");

    addDigest(digest, cl.getName());

    addDigest(digest, cl.getModifiers());

    Class superClass = cl.getSuperclass();
    if (superClass != null)
      addDigest(digest, superClass.getName());

    Class []interfaces = cl.getInterfaces();
    for (int i = 0; i < interfaces.length; i++)
      addDigest(digest, interfaces[i].getName());

    Field []fields = cl.getDeclaredFields();

    Arrays.sort(fields, new FieldComparator());

    if (_checkFields) {
      for (Field field : fields) {
        if (Modifier.isPrivate(field.getModifiers())
            && ! _checkPrivate)
          continue;
        if (Modifier.isProtected(field.getModifiers())
            && ! _checkProtected)
          continue;
        
        addDigest(digest, field.getName());
        addDigest(digest, field.getModifiers());
        addDigest(digest, field.getType().getName());

        addDigest(digest, field.getAnnotations());
      }
    }

    Method []methods = cl.getDeclaredMethods();
    Arrays.sort(methods, new MethodComparator());
    
    for (int i = 0; i < methods.length; i++) {
      Method method = methods[i];

      if (Modifier.isPrivate(method.getModifiers()) && ! _checkPrivate)
        continue;
      if (Modifier.isProtected(method.getModifiers()) && ! _checkProtected)
        continue;
      if (Modifier.isStatic(method.getModifiers()) && ! _checkStatic)
        continue;
        
      addDigest(digest, method.getName());
      addDigest(digest, method.getModifiers());
      addDigest(digest, method.getName());

      Class []param = method.getParameterTypes();
      for (int j = 0; j < param.length; j++)
        addDigest(digest, param[j].getName());

      addDigest(digest, method.getReturnType().getName());

      Class []exn = method.getExceptionTypes();
      for (int j = 0; j < exn.length; j++)
        addDigest(digest, exn[j].getName());

      addDigest(digest, method.getAnnotations());
    }
    
    byte []digestBytes = new byte[256];
    
    int len = digest.digest(digestBytes, 0, digestBytes.length);
    
    return digestToBase64(digestBytes, len);
  } catch (Exception e) {
    log.log(Level.FINER, e.toString(), e);

    return "";
  }
}
 
Example 17
Source File: TranslateExceptions.java    From FoxTelem with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Instruments methods of cjClazz defined in jdbcClass.
 * 
 * @param cjClazz
 *            CtClass to be instrumented.
 * @param jdbcClass
 *            Class from JDBC specification where methods descriptors to be get.
 * @param declaredMethodsOnly
 *            true - instrument methods declared in this class, false - also instrument inherited methods
 * @param exceptionInterceptorStr
 *            exception interceptor reference as a string
 * @throws Exception
 *             if an error occurs
 */
private static void instrumentJdbcMethods(CtClass cjClazz, Class<?> jdbcClass, boolean declaredMethodsOnly, String exceptionInterceptorStr)
        throws Exception {
    System.out.println("---");
    System.out.println(cjClazz.getName());

    Method[] methods;
    if (declaredMethodsOnly) {
        // instrument methods declared in this class which throws SQLException
        methods = jdbcClass.getDeclaredMethods();
    } else {
        // instrument all methods, declared in this class and it's superclasses, which throws SQLException
        methods = jdbcClass.getMethods();
    }

    for (Method method : methods) {
        CtMethod ctm = null;
        String prefix = "SKIPPED:         ";
        for (Class<?> exc : method.getExceptionTypes()) {
            if (exc.equals(SQLException.class)) {
                prefix = "INSTRUMENTING... ";
                String jdbcClassName = method.getName();
                List<CtClass> params = new LinkedList<>();
                for (Class<?> param : method.getParameterTypes()) {
                    params.add(pool.get(param.getName()));
                }
                try {
                    ctm = cjClazz.getDeclaredMethod(jdbcClassName, params.toArray(new CtClass[0]));
                } catch (NotFoundException ex) {
                    // Just ignoring because the only reason is that the method is implemented in superclass
                    prefix = "NOT FOUND:       ";
                }
                break;
            }
        }
        System.out.print(prefix);
        System.out.print(method.toGenericString());
        if (ctm != null) {
            if (catchRuntimeException(cjClazz, ctm, exceptionInterceptorStr, false)) {
                System.out.print(" ... DONE.");
            } else {
                System.out.print(" ... ALREADY PROCESSED!!!");
            }
        }
        System.out.println();
    }

}
 
Example 18
Source File: RuntimeModeler.java    From openjdk-8-source with GNU General Public License v2.0 4 votes vote down vote up
/**
 * models the exceptions thrown by <code>method</code> and adds them to the <code>javaMethod</code>
 * runtime model object
 * @param javaMethod the runtime model object to add the exception model objects to
 * @param method the <code>method</code> from which to find the exceptions to model
 */
protected void processExceptions(JavaMethodImpl javaMethod, Method method) {
    Action actionAnn = getAnnotation(method, Action.class);
    FaultAction[] faultActions = {};
    if(actionAnn != null)
        faultActions = actionAnn.fault();
    for (Class<?> exception : method.getExceptionTypes()) {

        //Exclude RuntimeException, RemoteException and Error etc
        if (!EXCEPTION_CLASS.isAssignableFrom(exception))
            continue;
        if (RUNTIME_EXCEPTION_CLASS.isAssignableFrom(exception) || REMOTE_EXCEPTION_CLASS.isAssignableFrom(exception))
            continue;

        Class exceptionBean;
        Annotation[] anns;
        WebFault webFault = getAnnotation(exception, WebFault.class);
        Method faultInfoMethod = getWSDLExceptionFaultInfo(exception);
        ExceptionType exceptionType = ExceptionType.WSDLException;
        String namespace = targetNamespace;
        String name = exception.getSimpleName();
        String beanPackage = packageName + PD_JAXWS_PACKAGE_PD;
        if (packageName.length() == 0)
            beanPackage = JAXWS_PACKAGE_PD;
        String className = beanPackage+ name + BEAN;
        String messageName = exception.getSimpleName();
        if (webFault != null) {
            if (webFault.faultBean().length()>0)
                className = webFault.faultBean();
            if (webFault.name().length()>0)
                name = webFault.name();
            if (webFault.targetNamespace().length()>0)
                namespace = webFault.targetNamespace();
            if (webFault.messageName().length()>0)
                messageName = webFault.messageName();
        }
        if (faultInfoMethod == null)  {
            exceptionBean = getExceptionBeanClass(className, exception, name, namespace);
            exceptionType = ExceptionType.UserDefined;
            anns = getAnnotations(exceptionBean);
        } else {
            exceptionBean = faultInfoMethod.getReturnType();
            anns = getAnnotations(faultInfoMethod);
        }
        QName faultName = new QName(namespace, name);
        TypeInfo typeRef = new TypeInfo(faultName, exceptionBean, anns);
        CheckedExceptionImpl checkedException =
            new CheckedExceptionImpl(javaMethod, exception, typeRef, exceptionType);
        checkedException.setMessageName(messageName);
        for(FaultAction fa: faultActions) {
            if(fa.className().equals(exception) && !fa.value().equals("")) {
                checkedException.setFaultAction(fa.value());
                break;
            }
        }
        javaMethod.addException(checkedException);
    }
}
 
Example 19
Source File: ReferenceInvocationHandler.java    From mango with Apache License 2.0 4 votes vote down vote up
private boolean checkMethodExceptionSignature(Method method) {
    Class<?>[] exps = method.getExceptionTypes();
    return exps!=null && exps.length>0;
}
 
Example 20
Source File: ReflectionUtils2.java    From super-cloudops with Apache License 2.0 3 votes vote down vote up
/**
 * 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
 * @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) {
	notNull(method, "Method must not be null");
	Class<?>[] declaredExceptions = method.getExceptionTypes();
	for (Class<?> declaredException : declaredExceptions) {
		if (declaredException.isAssignableFrom(exceptionType)) {
			return true;
		}
	}
	return false;
}