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.espertech.esper.epl.expression.dot.ExprDotMethodEvalDuck.java

private FastMethod getFastMethod(Class clazz) {
    try {/*from w  ww  .j  a  v  a  2 s.co m*/
        Method method = methodResolutionService.resolveMethod(clazz, methodName, parameterTypes,
                new boolean[parameterTypes.length], new boolean[parameterTypes.length]);
        FastClass declaringClass = FastClass.create(Thread.currentThread().getContextClassLoader(),
                method.getDeclaringClass());
        return declaringClass.getMethod(method);
    } catch (Exception e) {
        log.debug("Not resolved for class '" + clazz.getName() + "' method '" + methodName + "'");
    }
    return null;
}

From source file:com.bstek.dorado.data.entity.BeanEntityEnhancer.java

protected synchronized void buildReflectionCahce() throws Exception {
    synchronized (cachedTypes) {
        if (!cachedTypes.contains(beanType)) {
            cachedTypes.add(beanType);/*  w  w  w . j a  v a  2  s.  c o m*/

            Map<String, Boolean> properties = new Hashtable<String, Boolean>();
            Map<Method, String> readMethods = new Hashtable<Method, String>();
            Map<Method, String> writeMethods = new Hashtable<Method, String>();
            PropertyDescriptor[] propertyDescriptors = PropertyUtils.getPropertyDescriptors(beanType);
            for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
                String property = propertyDescriptor.getName();
                if (propertyDescriptor.getReadMethod() == null) {
                    continue;
                }

                properties.put(property, Boolean.valueOf(propertyDescriptor.getWriteMethod() != null));

                Method readMethod = propertyDescriptor.getReadMethod();
                Method writeMethod = propertyDescriptor.getWriteMethod();
                if (readMethod != null) {
                    if (readMethod.getDeclaringClass() != beanType) {
                        readMethod = beanType.getMethod(readMethod.getName(), readMethod.getParameterTypes());
                    }
                    readMethods.put(readMethod, property);
                }
                if (writeMethod != null) {
                    if (writeMethod.getDeclaringClass() != beanType) {
                        writeMethod = beanType.getMethod(writeMethod.getName(),
                                writeMethod.getParameterTypes());
                    }
                    writeMethods.put(writeMethod, property);
                }
            }
            propertiesCache.put(beanType, properties);
            readMethodsCache.put(beanType, readMethods);
            writeMethodsCache.put(beanType, writeMethods);
            this.properties = properties;
            this.readMethods = readMethods;
            this.writeMethods = writeMethods;
        } else {
            this.properties = propertiesCache.get(beanType);
            this.readMethods = readMethodsCache.get(beanType);
            this.writeMethods = writeMethodsCache.get(beanType);
        }
    }
}

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

public void validate(StreamTypeService streamTypeService, MethodResolutionService methodResolutionService,
        ViewResourceDelegate viewResourceDelegate, TimeProvider timeProvider, VariableService variableService,
        ExprEvaluatorContext exprEvaluatorContext) throws ExprValidationException {
    ExprNodeUtility.validate(chainSpec, streamTypeService, methodResolutionService, viewResourceDelegate,
            timeProvider, variableService, exprEvaluatorContext);

    // 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()) {
        ExprEvaluator eval = childNode.getExprEvaluator();
        childEvals[count] = eval;// ww w  .  j av  a2s .  co  m
        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;
    try {
        Method method = methodResolutionService.resolveMethod(className, firstItem.getName(), paramTypes);
        FastClass declaringClass = FastClass.create(Thread.currentThread().getContextClassLoader(),
                method.getDeclaringClass());
        staticMethod = declaringClass.getMethod(method);
    } catch (Exception e) {
        throw new ExprValidationException(e.getMessage());
    }

    ExprDotEval[] eval = ExprDotNodeUtility.getChainEvaluators(staticMethod.getReturnType(), chainList,
            methodResolutionService, false);
    evaluator = new ExprStaticMethodEvalInvoke(className, staticMethod, childEvals, isConstantParameters, eval);
}

From source file:hu.bme.mit.sette.tools.catg.CatgGenerator.java

private void createGeneratedFiles() throws IOException {
    // generate main() for each snippet
    for (SnippetContainer container : getSnippetProject().getModel().getContainers()) {
        if (container.getRequiredJavaVersion().compareTo(getTool().getSupportedJavaVersion()) > 0) {
            // TODO enhance message
            System.err.println("Skipping container: " + container.getJavaClass().getName()
                    + " (required Java version: " + container.getRequiredJavaVersion() + ")");
            continue;
        }/*from  w  w  w  .  java  2s  . c o m*/

        snippetLoop: for (Snippet snippet : container.getSnippets().values()) {
            Method method = snippet.getMethod();
            Class<?> javaClass = method.getDeclaringClass();
            Class<?>[] parameterTypes = method.getParameterTypes();

            // generate main()
            JavaClassWithMain main = new JavaClassWithMain();
            main.setPackageName(javaClass.getPackage().getName());
            main.setClassName(javaClass.getSimpleName() + '_' + method.getName());

            main.imports().add(javaClass.getName());
            main.imports().add("catg.CATG");

            String[] paramNames = new String[parameterTypes.length];
            List<String> createVariableLines = new ArrayList<>(parameterTypes.length);
            List<String> sysoutVariableLines = new ArrayList<>(parameterTypes.length);

            int i = 0;
            for (Class<?> parameterType : parameterTypes) {
                String paramName = "param" + (i + 1);
                String varType = CatgGenerator.getTypeString(parameterType);
                String catgRead = CatgGenerator.createCatgRead(parameterType);

                if (varType == null || catgRead == null) {
                    // TODO make better
                    System.err.println("Method has an unsupported parameter type: " + parameterType.getName()
                            + " (method: " + method.getName() + ")");
                    continue snippetLoop;
                }

                paramNames[i] = paramName;
                // e.g.: int param1 = CATG.readInt(0);
                createVariableLines.add(String.format("%s %s = %s;", varType, paramName, catgRead));
                // e.g.: System.out.println("  int param1 = " + param1);
                sysoutVariableLines.add(String.format("System.out.println(\"  %s %s = \" + %s);", varType,
                        paramName, paramName));
                i++;
            }

            main.codeLines().addAll(createVariableLines);

            main.codeLines().add("");

            main.codeLines().add(String.format("System.out.println(\"%s#%s\");", javaClass.getSimpleName(),
                    method.getName()));
            main.codeLines().addAll(sysoutVariableLines);

            String functionCall = String.format("%s.%s(%s)", javaClass.getSimpleName(), method.getName(),
                    StringUtils.join(paramNames, ", "));

            Class<?> returnType = method.getReturnType();

            if (Void.TYPE.equals(returnType) || Void.class.equals(returnType)) {
                // void return type
                main.codeLines().add(functionCall + ';');
                main.codeLines().add("System.out.println(\"  result: void\");");
            } else {
                // non-void return type
                main.codeLines().add("System.out.println(\"  result: \" + " + functionCall + ");");
            }

            // save files
            String relativePath = JavaFileUtils.packageNameToFilename(main.getFullClassName());
            String relativePathMain = relativePath + '.' + JavaFileUtils.JAVA_SOURCE_EXTENSION;

            File targetMainFile = new File(getRunnerProjectSettings().getGeneratedDirectory(),
                    relativePathMain);
            FileUtils.forceMkdir(targetMainFile.getParentFile());
            FileUtils.write(targetMainFile, main.generateJavaCode().toString());
        }
    }
}

From source file:org.nabucco.alfresco.enhScriptEnv.common.script.aop.ListLikeMapAdapterInterceptor.java

/**
 * {@inheritDoc}/*from  w ww .j  a  v  a  2 s.  c  om*/
 */
@Override
public Object invoke(final MethodInvocation invocation) throws Throwable {
    final Object result;

    final Method method = invocation.getMethod();
    final Class<?> declaringClass = method.getDeclaringClass();
    final Object this1 = invocation.getThis();
    if ((List.class.equals(declaringClass) || Collection.class.equals(declaringClass))
            && !(this1 instanceof List<?>)) {
        if (invocation instanceof ProxyMethodInvocation
                && ((ProxyMethodInvocation) invocation).getProxy() instanceof Map<?, ?>) {
            final Map<?, ?> map = (Map<?, ?>) ((ProxyMethodInvocation) invocation).getProxy();
            final String methodName = method.getName();

            boolean proceedInvocation = false;
            Object adaptedResult = null;

            final Object[] arguments = invocation.getArguments();
            final Class<?>[] parameterTypes = method.getParameterTypes();

            // String-switch not supported in Java < 8
            switch (ListMethodName.methodLiteralOf(methodName)) {
            case SIZE:
                adaptedResult = Integer.valueOf(map.size());
                break;
            case ISEMPTY:
                adaptedResult = Boolean.valueOf(map.isEmpty());
                break;
            case CONTAINS:
                adaptedResult = Boolean.valueOf(map.containsValue(arguments[0]));
                break;
            case ITERATOR:
                adaptedResult = map.values().iterator();
                break;
            case TOARRAY:
                adaptedResult = arguments.length == 1 ? map.values().toArray((Object[]) arguments[0])
                        : map.values().toArray();
                break;
            case CONTAINSALL:
                adaptedResult = Boolean.valueOf(map.values().containsAll((Collection<?>) arguments[0]));
                break;
            case REMOVEALL:
                adaptedResult = Boolean.valueOf(map.values().removeAll((Collection<?>) arguments[0]));
                break;
            case INDEXOF: {
                int idx = 0;
                int foundIdx = -1;
                final Iterator<?> valueIterator = map.values().iterator();
                while (valueIterator.hasNext()) {
                    final Object el = valueIterator.next();
                    if (el == arguments[0] || (arguments[0] != null && arguments[0].equals(el))) {
                        foundIdx = idx;
                        break;
                    }
                    idx++;
                }
                adaptedResult = Integer.valueOf(foundIdx);
            }
                break;
            case LASTINDEXOF: {
                int idx = 0;
                int foundIdx = -1;
                final Iterator<?> valueIterator = map.values().iterator();
                while (valueIterator.hasNext()) {
                    final Object el = valueIterator.next();
                    if (el == arguments[0] || (arguments[0] != null && arguments[0].equals(el))) {
                        foundIdx = idx;
                    }
                    idx++;
                }
                adaptedResult = Integer.valueOf(foundIdx);
            }
                break;
            case GET: {
                final int targetIdx = ((Integer) arguments[0]).intValue();

                if (targetIdx < 0 || targetIdx >= map.size()) {
                    throw new IndexOutOfBoundsException();
                }

                int idx = 0;
                Object found = null;
                final Iterator<?> valueIterator = map.values().iterator();
                while (valueIterator.hasNext()) {
                    final Object el = valueIterator.next();
                    if (idx == targetIdx) {
                        found = el;
                        break;
                    }
                    idx++;
                }
                adaptedResult = found;
            }
                break;
            case REMOVE: {
                if (arguments[0] instanceof Integer && int.class.equals(parameterTypes[0])) {
                    final int targetIdx = ((Integer) arguments[0]).intValue();

                    if (targetIdx < 0 || targetIdx >= map.size()) {
                        throw new IndexOutOfBoundsException();
                    }

                    int idx = 0;
                    final Iterator<?> keyIterator = map.keySet().iterator();
                    Object keyToRemove = null;
                    while (keyIterator.hasNext()) {
                        final Object el = keyIterator.next();
                        if (idx == targetIdx) {
                            keyToRemove = el;
                            break;
                        }
                        idx++;
                    }

                    adaptedResult = keyToRemove != null ? map.remove(keyToRemove) : null;
                } else {
                    adaptedResult = Boolean.valueOf(map.values().remove(arguments[0]));
                }
            }
                break;
            case RETAINALL:
                adaptedResult = Boolean.valueOf(map.values().retainAll((Collection<?>) arguments[0]));
                break;
            case CLEAR:
                map.clear();
                break;
            case LISTITERATOR: // fallthrough
            case SUBLIST: // fallthrough
            case SET:// fallthrough
            case ADD:// fallthrough
            case ADDALL:
                // not supported
                throw new UnsupportedOperationException();
            default:
                proceedInvocation = true;
            }

            if (proceedInvocation) {
                // may fail (if we have forgotten to map a specific operation or a new operation may have been introduced)
                result = invocation.proceed();
            } else {
                result = adaptedResult;
            }
        } else {
            // may fail when other interceptors / target do not support List
            result = invocation.proceed();
        }
    } else {
        // may fail when List was declaring class but type of "this" does not support this interceptor
        result = invocation.proceed();
    }

    return result;
}

From source file:com.laxser.blitz.lama.core.LamaDaoInvocationHandler.java

@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

    if (logger.isDebugEnabled()) {
        logger.debug("invoking  " + definition.getDAOClazz().getName() + "#" + method.getName());
    }//from   www  .j  av  a  2s .c o m

    if (Object.class == method.getDeclaringClass()) {
        String methodName = method.getName();
        if (methodName.equals("toString")) {
            return LamaDaoInvocationHandler.this.toString();
        }
        if (methodName.equals("hashCode")) {
            return definition.getDAOClazz().hashCode() * 13 + this.hashCode();
        }
        if (methodName.equals("equals")) {
            return args[0] == proxy;
        }
        if (methodName.equals("clone")) {
            throw new CloneNotSupportedException("clone is not supported for jade dao.");
        }
        throw new UnsupportedOperationException(definition.getDAOClazz().getName() + "#" + method.getName());
    }

    LamaOperation operation = jdbcOperations.get(method);
    if (operation == null) {
        synchronized (jdbcOperations) {
            operation = jdbcOperations.get(method);
            if (operation == null) {
                Modifier modifier = new Modifier(definition, method);
                operation = jdbcOperationFactory.getOperation(dataAccess, modifier);
                jdbcOperations.put(method, operation);
            }
        }
    }
    //
    // ?  Map
    Map<String, Object> parameters;
    if (args == null || args.length == 0) {
        parameters = new HashMap<String, Object>(4);
    } else {
        parameters = new HashMap<String, Object>(args.length * 2 + 4);
        SQLParam[] sqlParams = operation.getModifier().getParameterAnnotations(SQLParam.class);
        for (int i = 0; i < args.length; i++) {
            parameters.put(":" + (i + 1), args[i]);
            SQLParam sqlParam = sqlParams[i];
            if (sqlParam != null) {
                parameters.put(sqlParam.value(), args[i]);
            }
        }
    }
    //
    if (logger.isDebugEnabled()) {
        StringBuilder sb = new StringBuilder();
        sb.append("invoking ").append(definition.getDAOClazz().getName()).append("#").append(method.getName())
                .append("\n");
        sb.append("\toperation: ").append(operation.getClass().getSimpleName()).append("\n");
        sb.append("\tsql: ").append(operation.getModifier().getAnnotation(SQL.class).value()).append("\n");
        sb.append("\tparams: ");
        ArrayList<String> keys = new ArrayList<String>(parameters.keySet());
        Collections.sort(keys);
        for (String key : keys) {
            sb.append(key).append("='").append(parameters.get(key)).append("'  ");
        }
        logger.debug(sb.toString());
    }

    return operation.execute(parameters);
}

From source file:GenericClass.java

/**
 * Return real, "generics dereferenced", parameter types for the given method.
 * //w  w w.j  av a 2 s.  c o m
 * @param method
 *          The method to analyze
 * @return The real classes, dereferencing generics
 */
public GenericClass[] getParameterTypes(Method method) {
    Class<?> declaring = method.getDeclaringClass();
    String declname = declaring.getName();

    Type[] parameterTypes = method.getGenericParameterTypes();
    GenericClass[] ret = new GenericClass[parameterTypes.length];
    for (int i = 0; i < parameterTypes.length; i++) {
        Type type = parameterTypes[i];
        if (type instanceof Class) {
            ret[i] = forClass((Class<?>) type);
        } else if (type instanceof TypeVariable) {
            String name = ((TypeVariable<?>) type).getName();
            Class<?> sub = genericMap.get(declname + "--" + name);
            if (sub == null)
                sub = Object.class;
            ret[i] = forClass(sub);
        } else {
            ret[i] = forGenericType(type);
        }
    }
    return ret;
}

From source file:MBeanTyper.java

public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    if (MBeanTyper.DEBUG) {
        System.err.println("  ++ method=" + method.getName() + ",args=" + args);
    }/*from   w  w w.j  ava  2  s. co m*/
    try {
        if (method.getDeclaringClass() == Object.class) {
            String name = method.getName();
            if (name.equals("hashCode")) {
                return new Integer(this.hashCode());
            } else if (name.equals("toString")) {
                return this.toString();
            } else if (name.equals("equals")) {
                // FIXME: this needs to be reviewed - we should be
                // smarter about this ...
                return new Boolean(equals(args[0]));
            }
        } else if (isJMXAttribute(method) && (args == null || args.length <= 0)) {
            String name = method.getName().substring(3);
            return server.getAttribute(mbean, name);
        }

        String sig[] = (String[]) signatureCache.get(method);
        if (sig == null) {
            // get the method signature from the method argument directly
            // vs. the arguments passed, since there may be primitives that
            // are wrapped as objects in the arguments
            Class _args[] = method.getParameterTypes();
            if (_args != null && _args.length > 0) {
                sig = new String[_args.length];
                for (int c = 0; c < sig.length; c++) {
                    if (_args[c] != null) {
                        sig[c] = _args[c].getName();
                    }
                }
            } else {
                sig = new String[0];
            }
            signatureCache.put(method, sig);
        }
        return server.invoke(mbean, method.getName(), args, sig);
    } catch (Throwable t) {
        if (MBeanTyper.DEBUG) {
            t.printStackTrace();
        }
        if (t instanceof UndeclaredThrowableException) {
            UndeclaredThrowableException ut = (UndeclaredThrowableException) t;
            throw ut.getUndeclaredThrowable();
        } else if (t instanceof InvocationTargetException) {
            InvocationTargetException it = (InvocationTargetException) t;
            throw it.getTargetException();
        } else if (t instanceof MBeanException) {
            MBeanException me = (MBeanException) t;
            throw me.getTargetException();
        } else {
            throw t;
        }
    }
}

From source file:com.dbs.sdwt.jpa.JpaUtil.java

public String methodToProperty(Method m) {
    PropertyDescriptor[] pds = PropertyUtils.getPropertyDescriptors(m.getDeclaringClass());
    for (PropertyDescriptor pd : pds) {
        if (m.equals(pd.getReadMethod()) || m.equals(pd.getWriteMethod())) {
            return pd.getName();
        }//from w  w  w .jav a  2s .  c  o  m
    }
    return null;
}

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

@Override
public void initializeTypes(Method theMethod, Class<? extends Collection<?>> theOuterCollectionType,
        Class<? extends Collection<?>> theInnerCollectionType, Class<?> theParameterType) {
    if (theOuterCollectionType != null) {
        throw new ConfigurationException("Method '" + theMethod.getName() + "' in type '"
                + theMethod.getDeclaringClass().getCanonicalName() + "' is annotated with @"
                + Since.class.getName() + " but can not be of collection type");
    }//from ww  w.j av a  2  s .c  o m
    if (!ParameterUtil.getBindableIntegerTypes().contains(theParameterType)) {
        throw new ConfigurationException("Method '" + theMethod.getName() + "' in type '"
                + theMethod.getDeclaringClass().getCanonicalName() + "' is annotated with @"
                + Since.class.getName() + " but type '" + theParameterType
                + "' is an invalid type, must be one of: " + ParameterUtil.getBindableIntegerTypes());
    }
    myType = theParameterType;
}