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:net.abhinavsarkar.spelhelper.ImplicitMethodResolver.java

@Override
public MethodExecutor resolve(final EvaluationContext context, final Object targetObject, final String name,
        final List<TypeDescriptor> argumentTypes) throws AccessException {
    if (targetObject == null) {
        return null;
    }/*from  w  w  w. j  a v  a2  s . co  m*/
    Class<?> type = targetObject.getClass();
    String cacheKey = type.getName() + "." + name;
    if (CACHE.containsKey(cacheKey)) {
        MethodExecutor executor = CACHE.get(cacheKey);
        return executor == NULL_ME ? null : executor;
    }

    Method method = lookupMethod(context, type, name);
    if (method != null) {
        int modifiers = method.getModifiers();
        if (Modifier.isPublic(modifiers) && Modifier.isStatic(modifiers)) {
            Class<?>[] parameterTypes = method.getParameterTypes();
            Class<?> firstParamType = parameterTypes[0];
            if (parameterTypes.length > 0 && firstParamType.isAssignableFrom(type)) {
                List<TypeDescriptor> newArgumentTypes = new ArrayList<TypeDescriptor>();
                newArgumentTypes.add(TypeDescriptor.valueOf(firstParamType));
                newArgumentTypes.addAll(argumentTypes);

                MethodExecutor executor = delegate.resolve(context, method.getDeclaringClass(), name,
                        newArgumentTypes);
                MethodExecutor wrappedExecutor = executor == null ? null : new ImplicitMethodExecutor(executor);
                if (wrappedExecutor == null) {
                    CACHE.putIfAbsent(cacheKey, NULL_ME);
                }
                return wrappedExecutor;
            }
        }
    }
    CACHE.putIfAbsent(cacheKey, NULL_ME);
    return null;
}

From source file:de.bund.bva.pliscommon.serviceapi.core.aop.StelltLoggingKontextBereitInterceptor.java

/**
 * Ermittelt die StelltLoggingKontextBereit-Annotation.
 *
 * @param method/*from w  w  w. j a v  a2 s  .  co m*/
 *            Aufgerufene Methode.
 * @param targetClass
 *            Klasse, an der die Methode aufgerufen wurde.
 * @return Annotation StelltLoggingKontextBereit
 */
private StelltLoggingKontextBereit ermittleStelltLoggingKontextBereitAnnotation(Method method,
        Class<?> targetClass) {

    // Strategie fr die Ermittlung der Annotation ist aus AnnotationTransactionAttributeSource
    // bernommen.

    // Ignore CGLIB subclasses - introspect the actual user class.
    Class<?> userClass = ClassUtils.getUserClass(targetClass);
    // The method may be on an interface, but we need attributes from the target class.
    // If the target class is null, the method will be unchanged.
    Method specificMethod = ClassUtils.getMostSpecificMethod(method, userClass);
    // If we are dealing with method with generic parameters, find the original method.
    specificMethod = BridgeMethodResolver.findBridgedMethod(specificMethod);

    // First try is the method in the target class.
    StelltLoggingKontextBereit stelltLoggingKontextBereit = specificMethod
            .getAnnotation(StelltLoggingKontextBereit.class);
    if (stelltLoggingKontextBereit != null) {
        return stelltLoggingKontextBereit;
    }

    // Second try is the transaction attribute on the target class.
    stelltLoggingKontextBereit = specificMethod.getDeclaringClass()
            .getAnnotation(StelltLoggingKontextBereit.class);
    if (stelltLoggingKontextBereit != null) {
        return stelltLoggingKontextBereit;
    }

    if (specificMethod != method) {
        // Fallback is to look at the original method.
        stelltLoggingKontextBereit = method.getAnnotation(StelltLoggingKontextBereit.class);
        if (stelltLoggingKontextBereit != null) {
            return stelltLoggingKontextBereit;
        }

        // Last fallback is the class of the original method.
        return method.getDeclaringClass().getAnnotation(StelltLoggingKontextBereit.class);
    }

    return null;
}

From source file:org.apache.axis2.rpc.receivers.RPCMessageReceiver.java

/**
 * reflect and get the Java method - for each i'th param in the java method - get the first
 * child's i'th child -if the elem has an xsi:type attr then find the deserializer for it - if
 * not found, lookup deser for th i'th param (java type) - error if not found - deserialize &
 * save in an object array - end for//from  w w w .  j  a va 2  s  .co  m
 * <p/>
 * - invoke method and get the return value
 * <p/>
 * - look up serializer for return value based on the value and type
 * <p/>
 * - create response msg and add return value as grand child of <soap:body>
 *
 * @param inMessage incoming MessageContext
 * @param outMessage outgoing MessageContext
 * @throws AxisFault
 */

public void invokeBusinessLogic(MessageContext inMessage, MessageContext outMessage) throws AxisFault {
    Method method = null;
    try {
        // get the implementation class for the Web Service
        Object obj = getTheImplementationObject(inMessage);

        Class implClass = obj.getClass();

        AxisOperation op = inMessage.getOperationContext().getAxisOperation();
        method = (Method) (op.getParameterValue("myMethod"));
        // If the declaring class has changed, then the cached method is invalid, so we need to
        // reload it. This is to fix AXIS2-3947.
        if (method != null && method.getDeclaringClass() != implClass) {
            method = null;
        }
        AxisService service = inMessage.getAxisService();
        OMElement methodElement = inMessage.getEnvelope().getBody().getFirstElement();
        AxisMessage inAxisMessage = op.getMessage(WSDLConstants.MESSAGE_LABEL_IN_VALUE);
        String messageNameSpace = null;

        if (method == null) {
            String methodName = op.getName().getLocalPart();
            Method[] methods = implClass.getMethods();

            for (Method method1 : methods) {
                if (method1.isBridge()) {
                    continue;
                }
                if (method1.getName().equals(methodName)) {
                    method = method1;
                    op.addParameter("myMethod", method);
                    break;
                }
            }
            if (method == null) {
                throw new AxisFault("No such method '" + methodName + "' in class " + implClass.getName());
            }
        }
        Object resObject = null;
        if (inAxisMessage != null) {
            resObject = RPCUtil.invokeServiceClass(inAxisMessage, method, obj, messageNameSpace, methodElement,
                    inMessage);
        }

        SOAPFactory fac = getSOAPFactory(inMessage);

        // Handling the response
        AxisMessage outaxisMessage = op.getMessage(WSDLConstants.MESSAGE_LABEL_OUT_VALUE);
        if (outaxisMessage != null && outaxisMessage.getElementQName() != null) {
            messageNameSpace = outaxisMessage.getElementQName().getNamespaceURI();
        } else {
            messageNameSpace = service.getTargetNamespace();
        }

        OMNamespace ns = fac.createOMNamespace(messageNameSpace, service.getSchemaTargetNamespacePrefix());
        SOAPEnvelope envelope = fac.getDefaultEnvelope();
        OMElement bodyContent = null;

        if (WSDL2Constants.MEP_URI_ROBUST_IN_ONLY.equals(op.getMessageExchangePattern())) {
            OMElement bodyChild = fac.createOMElement(outMessage.getAxisMessage().getName(), ns);
            envelope.getBody().addChild(bodyChild);
            outMessage.setEnvelope(envelope);
            return;
        }
        Parameter generateBare = service.getParameter(Java2WSDLConstants.DOC_LIT_BARE_PARAMETER);
        if (generateBare != null && "true".equals(generateBare.getValue())) {
            RPCUtil.processResonseAsDocLitBare(resObject, service, envelope, fac, ns, bodyContent, outMessage);
        } else {
            RPCUtil.processResponseAsDocLitWrapped(resObject, service, method, envelope, fac, ns, bodyContent,
                    outMessage);
        }
        outMessage.setEnvelope(envelope);
    } catch (InvocationTargetException e) {
        String msg = null;
        Throwable cause = e.getCause();
        if (cause != null) {
            msg = cause.getMessage();
        }
        if (msg == null) {
            msg = "Exception occurred while trying to invoke service method "
                    + (method != null ? method.getName() : "null");
        }
        if (cause instanceof AxisFault) {
            log.debug(msg, cause);
            throw (AxisFault) cause;
        }

        Class[] exceptionTypes = method.getExceptionTypes();
        for (Class exceptionType : exceptionTypes) {
            if (exceptionType.getName().equals(cause.getClass().getName())) {
                // this is an bussiness logic exception so handle it properly
                String partQName = inMessage.getAxisService().getName() + getSimpleClassName(exceptionType);
                TypeTable typeTable = inMessage.getAxisService().getTypeTable();
                QName elementQName = typeTable.getQNamefortheType(partQName);
                SOAPFactory fac = getSOAPFactory(inMessage);
                OMElement exceptionElement = fac.createOMElement(elementQName);

                if (exceptionType.getName().equals(Exception.class.getName())) {
                    // this is an exception class. so create a element by hand and add the message
                    OMElement innterExceptionElement = fac.createOMElement(elementQName);
                    OMElement messageElement = fac.createOMElement("Message",
                            inMessage.getAxisService().getTargetNamespace(), null);
                    messageElement.setText(cause.getMessage());

                    innterExceptionElement.addChild(messageElement);
                    exceptionElement.addChild(innterExceptionElement);
                } else {
                    // if it is a normal bussiness exception we need to generate the schema assuming it is a pojo
                    QName innerElementQName = new QName(elementQName.getNamespaceURI(),
                            getSimpleClassName(exceptionType));
                    XMLStreamReader xr = BeanUtil.getPullParser(cause, innerElementQName, typeTable, true,
                            false);
                    StAXOMBuilder stAXOMBuilder = new StAXOMBuilder(OMAbstractFactory.getOMFactory(),
                            new StreamWrapper(xr));
                    OMElement documentElement = stAXOMBuilder.getDocumentElement();
                    exceptionElement.addChild(documentElement);
                }

                AxisFault axisFault = new AxisFault(cause.getMessage());
                axisFault.setDetail(exceptionElement);
                throw axisFault;
            }
        }

        log.error(msg, e);
        throw new AxisFault(msg, e);
    } catch (RuntimeException e) {
        log.error(e.getMessage(), e);
        throw AxisFault.makeFault(e);
    } catch (Exception e) {
        String msg = "Exception occurred while trying to invoke service method "
                + (method != null ? method.getName() : "null");
        log.error(msg, e);
        throw AxisFault.makeFault(e);
    }
}

From source file:jef.tools.reflect.ClassEx.java

/**
 * ??/* ww w .j ava 2 s . com*/
 * 
 * @param method
 * @return
 */
public Type getMethodReturnType(Method method) {
    ClassEx cw = this;
    method = getRealMethod(method);
    if (method.getDeclaringClass() != this.cls) {
        Type type = GenericUtils.getSuperType(null, cls, method.getDeclaringClass());
        cw = new ClassEx(type);
    }
    return BeanUtils.getBoundType(method.getGenericReturnType(), cw);
}

From source file:jef.tools.reflect.ClassEx.java

/**
 * ????/*w  w w. j  ava  2  s.  co  m*/
 * 
 * @param method
 * @return
 */
public Type[] getMethodParamTypes(Method method) {
    ClassEx cw = this;
    method = getRealMethod(method);
    if (method.getDeclaringClass() != this.cls) {
        Type type = GenericUtils.getSuperType(null, cls, method.getDeclaringClass());
        cw = new ClassEx(type);
    }
    Type[] types = method.getGenericParameterTypes();
    for (int i = 0; i < types.length; i++) {
        types[i] = BeanUtils.getBoundType(types[i], cw);
    }
    return types;
}

From source file:org.jdbcluster.privilege.PrivilegeCheckerImpl.java

/**
 * gets Field instance of property path// w w  w  .ja v a2 s . c  o m
 * 
 * @param propertyPath property path
 * @param propDesc PropertyDescriptor
 * @return Field instance
 */
private Field getPropertyField(String propertyPath, PropertyDescriptor propDesc) {
    Method propertyReadMethod = propDesc.getReadMethod();
    String mName = propertyReadMethod.getName();
    String pName = mName.substring(3, 4).toLowerCase() + mName.substring(4);
    Class clazzContainingProperty = propertyReadMethod.getDeclaringClass();
    Field f = JDBClusterUtil.getField(pName, clazzContainingProperty);
    if (f == null)
        throw new ConfigurationException("property [" + propertyPath + "] does not exist");
    return f;
}

From source file:com.aliyun.odps.mapred.conf.JobConf.java

private void onDeprecated(Method method) {
    set("odps.deprecated." + method.getDeclaringClass().getCanonicalName() + "." + method.getName(), "true");
    LOG.warn("Calling deprecated method:" + method);
}

From source file:com.gargoylesoftware.htmlunit.WebTestCase.java

/**
 * Generates an instrumented HTML file in the temporary dir to easily make a manual test in a real browser.
 * The file is generated only if the system property {@link #PROPERTY_GENERATE_TESTPAGES} is set.
 * @param content the content of the HTML page
 * @param expectedAlerts the expected alerts
 * @throws IOException if writing file fails
 *///  w w  w .  j  a  v a 2 s.  co  m
protected void createTestPageForRealBrowserIfNeeded(final String content, final List<String> expectedAlerts)
        throws IOException {

    // save the information to create a test for WebDriver
    generateTest_content_ = content;
    generateTest_expectedAlerts_ = expectedAlerts;
    final Method testMethod = findRunningJUnitTestMethod();
    generateTest_testName_ = testMethod.getDeclaringClass().getSimpleName() + "_" + testMethod.getName()
            + ".html";

    if (System.getProperty(PROPERTY_GENERATE_TESTPAGES) != null) {
        // should be optimized....

        // calls to alert() should be replaced by call to custom function
        String newContent = StringUtils.replace(content, "alert(", "htmlunitReserved_caughtAlert(");

        final String instrumentationJS = createInstrumentationScript(expectedAlerts);

        // first version, we assume that there is a <head> and a </body> or a </frameset>
        if (newContent.indexOf("<head>") > -1) {
            newContent = StringUtils.replaceOnce(newContent, "<head>", "<head>" + instrumentationJS);
        } else {
            newContent = StringUtils.replaceOnce(newContent, "<html>",
                    "<html>\n<head>\n" + instrumentationJS + "\n</head>\n");
        }
        final String endScript = "\n<script>htmlunitReserved_addSummaryAfterOnload();</script>\n";
        if (newContent.contains("</body>")) {
            newContent = StringUtils.replaceOnce(newContent, "</body>", endScript + "</body>");
        } else {
            LOG.info("No test generated: currently only content with a <head> and a </body> is supported");
        }

        final File f = File.createTempFile("TEST" + '_', ".html");
        FileUtils.writeStringToFile(f, newContent, "ISO-8859-1");
        LOG.info("Test file written: " + f.getAbsolutePath());
    } else {
        if (LOG.isDebugEnabled()) {
            LOG.debug("System property \"" + PROPERTY_GENERATE_TESTPAGES
                    + "\" not set, don't generate test HTML page for real browser");
        }
    }
}

From source file:jef.tools.reflect.ClassEx.java

/**
 * ??/*ww w.j  av  a2s.co  m*/
 * 
 * @param method
 * @param index
 * @return
 */
public Type getMethodParamType(Method method, int index) {
    ClassEx cw = this;
    method = getRealMethod(method);
    if (method.getDeclaringClass() != this.cls) {
        Type type = GenericUtils.getSuperType(null, cls, method.getDeclaringClass());
        cw = new ClassEx(type);
    }
    Type[] types = method.getGenericParameterTypes();
    if (index < 0 || index > types.length) {
        throw new IllegalArgumentException(StringUtils.concat("the method ", method.getName(), " has ",
                String.valueOf(types.length), " params, index=", String.valueOf(index), " is out of bound."));
    }
    return BeanUtils.getBoundType(types[index], cw);
}

From source file:ca.uhn.fhir.rest.method.BaseOutcomeReturningMethodBindingWithResourceParam.java

@SuppressWarnings("unchecked")
public BaseOutcomeReturningMethodBindingWithResourceParam(Method theMethod, FhirContext theContext,
        Class<?> theMethodAnnotation, Object theProvider) {
    super(theMethod, theContext, theMethodAnnotation, theProvider);

    ResourceParameter resourceParameter = null;

    int index = 0;
    for (IParameter next : getParameters()) {
        if (next instanceof ResourceParameter) {
            resourceParameter = (ResourceParameter) next;
            if (resourceParameter.getMode() != ResourceParameter.Mode.RESOURCE) {
                continue;
            }/*w ww. ja  v a 2s . co  m*/
            if (myResourceType != null) {
                throw new ConfigurationException(
                        "Method " + theMethod.getName() + " on type " + theMethod.getDeclaringClass()
                                + " has more than one @ResourceParam. Only one is allowed.");
            }

            myResourceType = resourceParameter.getResourceType();

            myResourceParameterIndex = index;
        } else if (next instanceof ConditionalParamBinder) {
            myConditionalUrlIndex = index;
        }
        index++;
    }

    if ((myResourceType == null || Modifier.isAbstract(myResourceType.getModifiers()))
            && (theProvider instanceof IResourceProvider)) {
        myResourceType = ((IResourceProvider) theProvider).getResourceType();
    }
    if (myResourceType == null) {
        throw new ConfigurationException("Unable to determine resource type for method: " + theMethod);
    }

    myResourceName = theContext.getResourceDefinition(myResourceType).getName();
    myIdParamIndex = MethodUtil.findIdParameterIndex(theMethod, getContext());
    if (myIdParamIndex != null) {
        myIdParamType = (Class<? extends IIdType>) theMethod.getParameterTypes()[myIdParamIndex];
    }

    if (resourceParameter == null) {
        throw new ConfigurationException("Method " + theMethod.getName() + " in type "
                + theMethod.getDeclaringClass().getCanonicalName()
                + " does not have a resource parameter annotated with @" + ResourceParam.class.getSimpleName());
    }

}