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:org.ext4spring.parameter.DefaultParameterResolver.java

protected <T extends Annotation> T findAnnotation(Class<T> annotationType, Method method, Operation operation,
        String paramName) {// w w  w .j a  va  2  s  .  c  o  m
    T annotation = method.getAnnotation(annotationType);
    if (annotation == null) {
        //not found on the specified method. for setters it looks for getter annotations
        if (Operation.SET.equals(operation)) {
            for (Method currMethod : method.getDeclaringClass().getMethods()) {
                if (currMethod.getName().endsWith(paramName)) {
                    if (currMethod.getAnnotation(annotationType) != null) {
                        return currMethod.getAnnotation(annotationType);
                    }
                }
            }
        }
    }
    return annotation;
}

From source file:com.gzj.tulip.jade.context.JadeInvocationHandler.java

@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    final boolean debugEnabled = logger.isDebugEnabled();
    if (debugEnabled) {
        logger.debug("invoking " + daoMetaData.getDAOClass().getName() + "#" + method.getName());
    }/*from  w  w w  .  j a  v  a  2s .c o m*/

    // object
    if (method.getDeclaringClass() == Object.class) {
        return invokeObjectMethod(proxy, method, args);
    }
    // ??DAOStatement
    Statement statement = getStatement(method);
    //
    // ?  Map
    Map<String, Object> parameters;
    StatementMetaData statemenetMetaData = statement.getMetaData();
    if (args == null || args.length == 0) {
        parameters = new HashMap<String, Object>(4);
    } else {
        parameters = new HashMap<String, Object>(args.length * 2 + 4);
        for (int i = 0; i < args.length; i++) {
            parameters.put(INDEX_NAMES[i], args[i]);
            SQLParam sqlParam = statemenetMetaData.getSQLParamAt(i);
            if (sqlParam != null) {
                parameters.put(sqlParam.value(), args[i]);
            }
        }
    }
    // logging
    if (debugEnabled) {
        logger.info("invoking " + statemenetMetaData);
    }

    // executing
    long begin = System.currentTimeMillis();
    final Object result = statement.execute(parameters);
    long cost = System.currentTimeMillis() - begin;

    // logging
    if (sqlLogger.isInfoEnabled()) {
        sqlLogger.info(statemenetMetaData + "\tcost " + cost + "ms.");
    }
    return result;
}

From source file:com.espertech.esper.epl.expression.ExprPlugInSingleRowNode.java

public void validate(ExprValidationContext validationContext) throws ExprValidationException {
    ExprNodeUtility.validate(chainSpec, validationContext);

    // get first chain item
    List<ExprChainedSpec> chainList = new ArrayList<ExprChainedSpec>(chainSpec);
    ExprChainedSpec firstItem = chainList.remove(0);

    // Get the types of the parameters for the first invocation
    Class[] paramTypes = new Class[firstItem.getParameters().size()];
    ExprEvaluator[] childEvals = new ExprEvaluator[firstItem.getParameters().size()];
    int count = 0;

    boolean allConstants = true;
    for (ExprNode childNode : firstItem.getParameters()) {
        if (childNode instanceof ExprLambdaGoesNode) {
            throw new ExprValidationException(
                    "Unexpected lambda-expression encountered as parameter to UDF or static method");
        }//from  w  w w.ja v a2  s.  c om
        ExprEvaluator eval = childNode.getExprEvaluator();
        childEvals[count] = eval;
        paramTypes[count] = eval.getType();
        count++;
        if (!(childNode.isConstantResult())) {
            allConstants = false;
        }
    }
    boolean isConstantParameters = allConstants && isUseCache;
    isReturnsConstantResult = isConstantParameters && chainList.isEmpty();

    // Try to resolve the method
    FastMethod staticMethod;
    Method method;
    try {
        method = validationContext.getMethodResolutionService().resolveMethod(clazz.getName(),
                firstItem.getName(), paramTypes);
        FastClass declaringClass = FastClass.create(Thread.currentThread().getContextClassLoader(),
                method.getDeclaringClass());
        staticMethod = declaringClass.getMethod(method);
    } catch (Exception e) {
        throw new ExprValidationException(e.getMessage());
    }

    // this may return a pair of null if there is no lambda or the result cannot be wrapped for lambda-function use
    ExprDotStaticMethodWrap optionalLambdaWrap = ExprDotStaticMethodWrapFactory.make(method,
            validationContext.getEventAdapterService(), chainList);
    ExprDotEvalTypeInfo typeInfo = optionalLambdaWrap != null ? optionalLambdaWrap.getTypeInfo()
            : ExprDotEvalTypeInfo.scalarOrUnderlying(method.getReturnType());

    ExprDotEval[] eval = ExprDotNodeUtility.getChainEvaluators(typeInfo, chainList, validationContext, false,
            new ExprDotNodeFilterAnalyzerInputStatic()).getChainWithUnpack();
    evaluator = new ExprDotEvalStaticMethod(validationContext.getStatementName(), clazz.getName(), staticMethod,
            childEvals, isConstantParameters, optionalLambdaWrap, eval);
}

From source file:com.espertech.esper.event.bean.BeanInstantiatorFactory.java

private static BeanInstantiator resolveFactoryMethod(BeanEventType beanEventType,
        EngineImportService engineImportService) throws EventBeanManufactureException {
    String factoryMethodName = beanEventType.getFactoryMethodName();

    int lastDotIndex = factoryMethodName.lastIndexOf('.');
    if (lastDotIndex == -1) {
        try {/* w w w .j a v  a2 s .c o  m*/
            Method method = engineImportService.resolveMethod(beanEventType.getUnderlyingType(),
                    factoryMethodName, new Class[0], new boolean[0], new boolean[0]);
            if (beanEventType.getFastClass() != null) {
                return new BeanInstantiatorByFactoryFastClass(beanEventType.getFastClass().getMethod(method));
            } else {
                return new BeanInstantiatorByFactoryReflection(method);
            }
        } catch (EngineImportException e) {
            String message = "Failed to resolve configured factory method '" + factoryMethodName
                    + "' expected to exist for class '" + beanEventType.getUnderlyingType() + "'";
            log.info(message, e);
            throw new EventBeanManufactureException(message, e);
        }
    }

    String className = factoryMethodName.substring(0, lastDotIndex);
    String methodName = factoryMethodName.substring(lastDotIndex + 1);
    try {
        Method method = engineImportService.resolveMethod(className, methodName, new Class[0], new boolean[0],
                new boolean[0]);
        if (beanEventType.getFastClass() != null) {
            FastClass fastClassFactory = FastClass.create(Thread.currentThread().getContextClassLoader(),
                    method.getDeclaringClass());
            return new BeanInstantiatorByFactoryFastClass(fastClassFactory.getMethod(method));
        } else {
            return new BeanInstantiatorByFactoryReflection(method);
        }
    } catch (EngineImportException e) {
        String message = "Failed to resolve configured factory method '" + methodName
                + "' expected to exist for class '" + className + "'";
        log.info(message, e);
        throw new EventBeanManufactureException(message, e);
    }
}

From source file:net.paoding.rose.jade.context.JadeInvocationHandler.java

@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    final boolean debugEnabled = logger.isDebugEnabled();
    if (debugEnabled) {
        logger.debug("invoking " + daoMetaData.getDAOClass().getName() + "#" + method.getName());
    }/*from  w  w  w . ja  v  a  2s . c  o  m*/

    // object
    if (method.getDeclaringClass() == Object.class) {
        return invokeObjectMethod(proxy, method, args);
    }
    // ??DAOStatement
    Statement statement = getStatement(method);
    //
    // ?  Map
    Map<String, Object> parameters;
    StatementMetaData statemenetMetaData = statement.getMetaData();
    if (args == null || args.length == 0) {
        parameters = new HashMap<String, Object>(4);
    } else {
        parameters = new HashMap<String, Object>(args.length * 2 + 4);
        for (int i = 0; i < args.length; i++) {
            parameters.put(INDEX_NAMES[i], args[i]);
            SQLParam sqlParam = statemenetMetaData.getSQLParamAt(i);
            if (sqlParam != null) {
                parameters.put(sqlParam.value(), args[i]);
            }
        }
    }
    // logging
    StringBuilder invocationInfo = null;
    if (debugEnabled) {
        invocationInfo = getInvocationInfo(statemenetMetaData, parameters);
        logger.debug("invoking " + invocationInfo.toString());
    }

    // executing
    long begin = System.currentTimeMillis();
    final Object result = statement.execute(parameters);
    long cost = System.currentTimeMillis() - begin;

    // logging
    if (logger.isInfoEnabled()) {
        if (invocationInfo == null) {
            invocationInfo = getInvocationInfo(statemenetMetaData, parameters);
        }
        logger.info("cost " + cost + "ms: " + invocationInfo);
    }
    return result;
}

From source file:com.garyclayburg.attributes.AttributeService.java

private Map<String, String> generateAttributes(User user, String targetId) {
    long startTime = System.nanoTime();
    HashMap<String, String> attributeValues = new HashMap<>(); //name,value

    if (user != null) {
        log.debug("start generating user attributes for userid: {} target: {}", user.getId(), targetId);
        detectedTargetIds = new HashSet<>();
        //        attributeClasses = findAnnotatedGroovyClasses(AttributesClass.class);
        while (!initiallyScanned) {
            //wait until thread to pre-load scripts has started (and locked annotatedGroovyClasses)
            //mostly needed for preventing race condition for fast-running unit tests
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                log.warn("kaboom", e);
            }/*from  w  w  w . ja va  2 s  .  c o  m*/
        }
        synchronized (groovyClassMap) {
            log.debug("checking for annotated classes");
            if (groovyClassMap.size() > 0) {

                for (Class groovyAttributeClass : groovyClassMap.values()) {
                    log.debug("checking for annotated classes: {}", groovyAttributeClass.getName());
                    try {
                        Object groovyObj = groovyAttributeClass.newInstance();
                        Set<Method> attributeMethods = getAllMethods(groovyAttributeClass,
                                withAnnotation(TargetAttribute.class));
                        log.debug("found {} annotated methods in class", attributeMethods.size());
                        List<Method> methodList = new ArrayList<>(attributeMethods);
                        for (Method method : methodList) {
                            String absMethodName = method.getDeclaringClass() + "." + method.getName();
                            TargetAttribute annotation = method.getAnnotation(TargetAttribute.class);
                            log.debug("attribute method found: {} target: {} attribute name: {}", absMethodName,
                                    annotation.target(), annotation.attributeName());
                            detectedTargetIds.add(annotation.target());
                            try {
                                String attributeValue = (String) method.invoke(groovyObj, user);
                                synchronized (groovyClassMap) {
                                    scriptErrors.remove(absMethodName);
                                }
                                log.debug(
                                        "attribute value eval  : {} target: {} attribute name: {} generated value: {}",
                                        absMethodName, annotation.target(), annotation.attributeName(),
                                        attributeValue);
                                String attributeName = annotation.attributeName().equals("") ? method.getName()
                                        : annotation.attributeName();
                                if (targetId == null) {
                                    attributeValues.put(attributeName, attributeValue);
                                } else if (targetId.equals(annotation.target())) {
                                    attributeValues.put(attributeName, attributeValue);
                                } else {
                                    log.debug("skipping attribute for target: {}", annotation.target());
                                }
                                log.debug("attribute name:value  for target {}: [{}:{}]", annotation.target(),
                                        attributeName, attributeValue);
                            } catch (IllegalAccessException e) {
                                log.warn("Cannot invoke attribute method in groovy: {}", absMethodName, e);
                                synchronized (groovyClassMap) {
                                    scriptErrors.put(absMethodName, e);
                                }
                            } catch (InvocationTargetException e) {
                                log.warn("Cannot call groovy attribute method: {}", absMethodName, e);
                                synchronized (groovyClassMap) {
                                    scriptErrors.put(absMethodName, e);
                                }
                            }

                        }
                    } catch (InstantiationException e) {
                        log.warn("Cannot check groovy script for generated attributes: "
                                + groovyAttributeClass.getName(), e);
                    } catch (IllegalAccessException e) {
                        log.warn("Cannot check groovy script for generated attributes: ", e);
                    }

                }
            } else {
                log.warn(
                        "No groovy scripts found with @AttributesClass annotation. Users will not have generated attributes");
            }
        }
        long endTime = System.nanoTime();
        log.info("Generated {} user attributes for userid {} in {} secs:  ", attributeValues.size(),
                user.getId(), ((endTime - startTime) / 1000000000.0));
    }
    return attributeValues;
}

From source file:org.ff4j.aop.FeatureAdvisor.java

private Object callAlterBeanMethod(final MethodInvocation pMInvoc, String alterBean, Logger targetLogger)
        throws Throwable {
    Method method = pMInvoc.getMethod();
    targetLogger.debug("FeatureFlipping on method:{} class:{}", method.getName(),
            method.getDeclaringClass().getName());
    // invoke same method (interface) with another spring bean (ff.alterBean())
    try {/*from ww w . j ava 2 s  .co m*/
        return method.invoke(appCtx.getBean(alterBean, method.getDeclaringClass()), pMInvoc.getArguments());
    } catch (InvocationTargetException invocationTargetException) {
        if (!ff4j.isAlterBeanThrowInvocationTargetException() && invocationTargetException.getCause() != null) {
            throw invocationTargetException.getCause();
        }
        throw makeIllegalArgumentException(
                "ff4j-aop: Cannot invoke method " + method.getName() + " on bean " + alterBean,
                invocationTargetException);
    } catch (Exception exception) {
        throw makeIllegalArgumentException(
                "ff4j-aop: Cannot invoke method " + method.getName() + " on bean " + alterBean, exception);
    }
}

From source file:edu.cornell.mannlib.vitro.webapp.web.beanswrappers.ReadOnlyBeansWrapper.java

@SuppressWarnings("rawtypes")
@Override// ww w.j a  va  2s  .  co  m
protected void finetuneMethodAppearance(Class cls, Method method, MethodAppearanceDecision decision) {

    // How to define a setter? This is a weak approximation: a method whose name
    // starts with "set" or returns void.
    if (method.getName().startsWith("set")) {
        decision.setExposeMethodAs(null);

    } else if (method.getReturnType().getName().equals("void")) {
        decision.setExposeMethodAs(null);

    } else {

        Class<?> declaringClass = method.getDeclaringClass();
        if (declaringClass.equals(java.lang.Object.class)) {
            decision.setExposeMethodAs(null);

        } else {
            Package pkg = declaringClass.getPackage();
            if (pkg.getName().equals("java.util")) {
                decision.setExposeMethodAs(null);
            }
        }
    }
}

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

private LambadaFunctionDefinition extractFunctionDefinitions(Method m) throws Exception {
    LambadaFunction lF = m.getAnnotation(LambadaFunction.class);

    final LambadaFunctionDefinition result = new LambadaFunctionDefinition();

    final String name = defaultIfBlank(lF.name(), m.getName());

    result.setName(name); // #1

    final String handler = m.getDeclaringClass().getCanonicalName() + "::" + m.getName();

    result.setAlias(lF.alias());// www  .j  a v  a2 s  .  com

    result.setHandler(handler);

    result.setMemorySize(lF.memorySize()); // #2

    if (isNotBlank(lF.role())) {
        result.setRole(lF.role()); // #3
    }

    result.setTimeout(lF.timeout()); // #4

    if (isNotBlank(lF.description())) {
        result.setDescription(lF.description()); // #5
    }

    result.setBindings(asList(lF.bindings()));

    if (null != lF.api() && 1 == lF.api().length) {
        ApiGateway apiGatewayAnn = lF.api()[0];

        APIGatewayDefinition def = new APIGatewayDefinition();

        def.setMethodType(APIGatewayDefinition.MethodType.valueOf(apiGatewayAnn.method().name()));
        def.setPath(apiGatewayAnn.path());
        def.setTemplate(apiGatewayAnn.template());
        def.setCorsEnabled(apiGatewayAnn.corsEnabled());

        def.setPatches(compilePatches(apiGatewayAnn.patches()));

        result.setApi(def);
    }

    return result;
}

From source file:org.synyx.hades.dao.orm.GenericDaoFactory.java

/**
 * Returns whether the given method is a custom DAO method.
 * //from w  w w .j  a  va2 s  .c o m
 * @param method
 * @param daoInterface
 * @return
 */
private boolean isCustomMethod(Method method, Class<?> daoInterface) {

    Class<?> declaringClass = method.getDeclaringClass();

    boolean isQueryMethod = declaringClass.equals(daoInterface);
    boolean isHadesDaoInterface = ClassUtils.isGenericDaoInterface(declaringClass);
    boolean isBaseClassMethod = isBaseClassMethod(method, daoInterface);

    return !(isHadesDaoInterface || isBaseClassMethod || isQueryMethod);
}