Example usage for java.lang.reflect Method getDeclaringClass

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

Introduction

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

Prototype

@Override
public Class<?> getDeclaringClass() 

Source Link

Document

Returns the Class object representing the class or interface that declares the method represented by this object.

Usage

From source file:com.appleframework.core.utils.ClassUtility.java

/** ??method?? */
public static String getSimpleMethodSignature(Method method, boolean withModifiers, boolean withReturnType,
        boolean withClassName, boolean withExceptionType) {
    if (method == null) {
        return null;
    }/*from  w  w w. j a  v  a2s. c  o  m*/

    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 (!isEmptyArray(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();
}

From source file:io.ingenieux.lambada.maven.ServeMojo.java

public void loadPathHandlers() throws Exception {
    final Set<Method> methodsAnnotatedWith = extractRuntimeAnnotations(ApiGateway.class);

    getLog().info("There are " + methodsAnnotatedWith.size() + " found methods.");

    for (Method m : methodsAnnotatedWith) {
        ApiGateway a = m.getAnnotation(ApiGateway.class);
        PathHandler pathHandler = new PathHandler();

        pathHandler.setPath(a.path());/*from   w w w.  j  a  va 2s . c o m*/
        pathHandler.setMethod(m);

        boolean bStatic = Modifier.isStatic(m.getModifiers());

        // TODO: ApiGateway
        getLog().info("Class: " + m.getDeclaringClass().getName());

        if (!bStatic) {
            try {
                pathHandler.setInstance(m.getDeclaringClass().newInstance());
            } catch (Exception exc) {
                throw new RuntimeException("Unable to create class " + m.getDeclaringClass(), exc);
            }
        }

        pathHandler.setMethodType(a.method());

        getLog().info("Added path handler: " + pathHandler);

        pathHandlers.add(pathHandler.build());
    }

}

From source file:org.springframework.cloud.netflix.feign.support.SpringMvcContractTests.java

@Test
public void testProcessAnnotations_SimpleGetMapping() throws Exception {
    Method method = TestTemplate_Simple.class.getDeclaredMethod("getMappingTest", String.class);
    MethodMetadata data = this.contract.parseAndValidateMetadata(method.getDeclaringClass(), method);

    assertEquals("/test/{id}", data.template().url());
    assertEquals("GET", data.template().method());
    assertEquals(MediaType.APPLICATION_JSON_VALUE, data.template().headers().get("Accept").iterator().next());

    assertEquals("id", data.indexToName().get(0).iterator().next());
}

From source file:org.springframework.cloud.netflix.feign.support.SpringMvcContractTests.java

@Test
public void testProcessAnnotations_SimplePostMapping() throws Exception {
    Method method = TestTemplate_Simple.class.getDeclaredMethod("postMappingTest", TestObject.class);
    MethodMetadata data = this.contract.parseAndValidateMetadata(method.getDeclaringClass(), method);

    assertEquals("", data.template().url());
    assertEquals("POST", data.template().method());
    assertEquals(MediaType.APPLICATION_JSON_VALUE, data.template().headers().get("Accept").iterator().next());

}

From source file:com.gs.jrpip.client.FastServletProxyInvocationHandler.java

protected Object invokeRemoteMethod(Object proxy, Method method, Object[] args) throws Throwable {
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("starting remote method {}.{}", method.getDeclaringClass(), method.getName());
    }//from  ww  w.jav a 2 s  .  c o  m
    RequestId requestId = new RequestId(this.proxyId);
    int retries = RETRY_COUNT;
    int state = SEND_PARAMETERS_STATE;
    Exception lastException = null;
    boolean checkServerStatus = false;
    while (retries > 0) {
        InputStream is = null;
        byte status = StreamBasedInvocator.FAULT_STATUS;
        Object returned = null;
        HttpClient httpClient = FastServletProxyFactory.getHttpClient(this.url);
        httpClient.getState().addCookies(this.cookies);
        boolean gotResult = false;
        HttpMethod postMethod = null;
        try {
            OutputStreamWriter writer = null;
            switch (state) {
            case SEND_PARAMETERS_STATE:
                writer = new ParameterWriter(proxy, method, args, requestId);
                break;
            case RECEIVE_RESULT_STATE:
                writer = new ResultResendWriter(requestId);
                break;
            }
            postMethod = this.getPostMethod(writer);

            this.setMethodTimeout(postMethod, method);

            httpClient.executeMethod(postMethod);

            this.cookies = httpClient.getState().getCookies();

            state = RECEIVE_RESULT_STATE;

            int code = postMethod.getStatusCode();

            if (code != 200) {
                checkServerStatus = true;
                this.analyzeServerErrorAndThrow(code, postMethod);
            }

            is = postMethod.getResponseBodyAsStream();

            //if (CAUSE_RANDOM_ERROR) if (Math.random() > ERROR_RATE) throw new IOException("Random error, for testing only!");

            status = (byte) is.read();
            if (status != StreamBasedInvocator.REQUEST_NEVER_ARRVIED_STATUS) {
                returned = this.getResult(method, args, is);
            }
            gotResult = true;
            is.close();
            is = null;
            postMethod.releaseConnection();
            postMethod = null;
        } catch (SocketTimeoutException e) {
            LOGGER.debug("Socket timeout reached for JRPIP invocation", e);
            throw new JrpipTimeoutException("Remote method " + method.getName() + " timed out." + this.url, e);
        } catch (NotSerializableException e) {
            throw new JrpipRuntimeException("Method arguments are not serializable!", e);
        } catch (ClassNotFoundException e) {
            throw new JrpipRuntimeException("Method call successfully completed but result class not found", e);
        } catch (Exception e) {
            retries--;
            lastException = e;
            LOGGER.debug("Exception in JRPIP invocation. Retries left {}", retries, e);
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    LOGGER.debug("Could not close stream. See previous exception for cause", e);
                }
            }
            if (postMethod != null) {
                postMethod.releaseConnection();
            }
        }
        if (gotResult) {
            switch (status) {
            case StreamBasedInvocator.OK_STATUS:
                ThankYouWriter.getINSTANCE().addRequest(this.url, this.cookies, requestId);
                if (LOGGER.isDebugEnabled()) {
                    LOGGER.debug("finished remote method normally {}.{}", method.getDeclaringClass(),
                            method.getName());
                }
                return returned;
            case StreamBasedInvocator.FAULT_STATUS:
                ThankYouWriter.getINSTANCE().addRequest(this.url, this.cookies, requestId);
                if (LOGGER.isDebugEnabled()) {
                    LOGGER.debug("finished remote method {}.{} with exception {}", method.getDeclaringClass(),
                            method.getName(), returned.getClass().getName(),
                            new JrpipRuntimeException("for tracing local invocation context"));
                }
                Class[] exceptions = method.getExceptionTypes();
                for (int i = 0; i < exceptions.length; i++) {
                    if (exceptions[i].isAssignableFrom(returned.getClass())) {
                        throw (Throwable) returned;
                    }
                }
                if (RuntimeException.class.isAssignableFrom(returned.getClass())) {
                    throw (RuntimeException) returned;
                }
                if (Error.class.isAssignableFrom(returned.getClass())) {
                    throw (Error) returned;
                }
                if (Throwable.class.isAssignableFrom(returned.getClass())
                        && !Exception.class.isAssignableFrom(returned.getClass())) {
                    throw (Throwable) returned;
                }
                throw new JrpipRuntimeException(
                        "Could not throw returned exception, as it was not declared in the method signature for method "
                                + method.getName(),
                        (Throwable) returned);
            case StreamBasedInvocator.REQUEST_NEVER_ARRVIED_STATUS:
                state = SEND_PARAMETERS_STATE;
                break;
            }
        } else {
            checkServerStatus = true;
        }
        if (checkServerStatus) {
            this.determineServerStatus(state == RECEIVE_RESULT_STATE);
            checkServerStatus = false;
        }
    }
    throw new JrpipRuntimeException(
            "Could not invoke remote method " + method.getName() + " while accessing " + this.url,
            lastException);
}

From source file:org.springframework.cloud.netflix.feign.support.SpringMvcContractTests.java

@Test
public void testProcessAnnotations_ListParamsWithoutName() throws Exception {
    Method method = TestTemplate_ListParamsWithoutName.class.getDeclaredMethod("getTest", List.class);
    MethodMetadata data = this.contract.parseAndValidateMetadata(method.getDeclaringClass(), method);

    assertEquals("/test", data.template().url());
    assertEquals("GET", data.template().method());
    assertEquals("[{id}]", data.template().queries().get("id").toString());
    assertNotNull(data.indexToExpander().get(0));
}

From source file:org.springframework.cloud.netflix.feign.support.SpringMvcContractTests.java

@Test
public void testProcessAnnotations_Class_AnnotationsGetAllTests() throws Exception {
    Method method = TestTemplate_Class_Annotations.class.getDeclaredMethod("getAllTests", String.class);
    MethodMetadata data = this.contract.parseAndValidateMetadata(method.getDeclaringClass(), method);

    assertEquals("/prepend/{classId}", data.template().url());
    assertEquals("GET", data.template().method());

    assertEquals("classId", data.indexToName().get(0).iterator().next());
}

From source file:com.amazonaws.mobileconnectors.dynamodbv2.dynamodbmapper.DynamoDBReflector.java

/**
 * Returns the setter corresponding to the getter given, or null if no such
 * setter exists.// w ww.jav  a  2  s.  c om
 */
Method getSetter(Method getter) {
    synchronized (setterCache) {
        if (!setterCache.containsKey(getter)) {
            String fieldName = ReflectionUtils.getFieldNameByGetter(getter, false);
            String setterName = "set" + fieldName;
            Method setter = null;
            try {
                setter = getter.getDeclaringClass().getMethod(setterName, getter.getReturnType());
            } catch (NoSuchMethodException e) {
                throw new DynamoDBMappingException("Expected a public, one-argument method called " + setterName
                        + " on class " + getter.getDeclaringClass(), e);
            } catch (SecurityException e) {
                throw new DynamoDBMappingException("No access to public, one-argument method called "
                        + setterName + " on class " + getter.getDeclaringClass(), e);
            }
            setterCache.put(getter, setter);
        }
        return setterCache.get(getter);
    }
}

From source file:org.springframework.cloud.netflix.feign.support.SpringMvcContractTests.java

@Test
public void testProcessAnnotations_ExtendedInterface() throws Exception {
    Method extendedMethod = TestTemplate_Extended.class.getMethod("getAllTests", String.class);
    MethodMetadata extendedData = this.contract.parseAndValidateMetadata(extendedMethod.getDeclaringClass(),
            extendedMethod);/*from w  w  w . java 2  s. co  m*/

    Method method = TestTemplate_Class_Annotations.class.getDeclaredMethod("getAllTests", String.class);
    MethodMetadata data = this.contract.parseAndValidateMetadata(method.getDeclaringClass(), method);

    assertEquals(extendedData.template().url(), data.template().url());
    assertEquals(extendedData.template().method(), data.template().method());

    assertEquals(data.indexToName().get(0).iterator().next(), data.indexToName().get(0).iterator().next());
}

From source file:org.springframework.cloud.netflix.feign.support.SpringMvcContractTests.java

@Test
public void testProcessAnnotationsOnMethod_Advanced_UnknownAnnotation() throws Exception {
    Method method = TestTemplate_Advanced.class.getDeclaredMethod("getTest", String.class, String.class,
            Integer.class);
    this.contract.parseAndValidateMetadata(method.getDeclaringClass(), method);

    // Don't throw an exception and this passes
}