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.github.reinert.jjschema.JsonSchemaGenerator.java

/**
 * Utility method to find properties from a Java Type following Beans Convention.
 *
 * @param type/*from   w  w  w .  j a v  a2  s  . c  o m*/
 * @return
 */
private <T> HashMap<Method, Field> findProperties(Class<T> type) {
    Field[] fields = type.getDeclaredFields();
    Method[] methods = type.getMethods();
    if (this.sortProperties) {
        // Ordering the properties
        Arrays.sort(methods, new Comparator<Method>() {
            public int compare(Method m1, Method m2) {
                return m1.getName().compareTo(m2.getName());
            }
        });
    }

    LinkedHashMap<Method, Field> props = new LinkedHashMap<Method, Field>();
    // get valid properties (get method and respective field (if exists))
    for (Method method : methods) {
        Class<?> declaringClass = method.getDeclaringClass();
        if (declaringClass.equals(Object.class) || Collection.class.isAssignableFrom(declaringClass)) {
            continue;
        }

        if (isGetter(method)) {
            boolean hasField = false;
            for (Field field : fields) {
                String name = getNameFromGetter(method);
                Attributes attribs = field.getAnnotation(Attributes.class);
                boolean process = true;
                if (this.processAnnotatedOnly && attribs == null) {
                    process = false;
                }

                if (process && field.getName().equalsIgnoreCase(name)) {
                    props.put(method, field);
                    hasField = true;
                    break;
                }
            }
            if (!hasField) {
                props.put(method, null);
            }
        }
    }
    return props;
}

From source file:jp.terasoluna.fw.validation.FieldChecksTest01.java

/**
 * testGetMethod03()/*  w  w w . j  a  v a 2s  .c  om*/
 * <br><br>
 *
 * ()
 * <br>
 * F
 * <br><br>
 * () va:not null<br>
 *         () paramClass:{Object.class,<br>
 *                 ValidatorAction.class,<br>
 *                 Field.class,<br>
 *                 ValidationErrors.class}<br>
 *         () va.getName:"requiredArray"<br>
 *
 * <br>
 * () Method:new FieldChecks()#validateRequired<br>
 *
 * <br>
 * va??????5???
 * ?validate??????
 * ?????????????
 * <br>
 *
 * @throws Exception ?????
 */
@Test
public void testGetMethod03() throws Exception {
    // ??
    va.setName("requiredArray");
    @SuppressWarnings("rawtypes")
    Class[] paramClass = { Object.class, ValidatorAction.class, Field.class, ValidationErrors.class };

    // 
    Method result = new FieldChecks().getMethod(va, paramClass);

    // 
    assertEquals(FieldChecks.class, result.getDeclaringClass());
    assertEquals("validateRequired", result.getName());
}

From source file:jp.terasoluna.fw.validation.FieldChecksTest01.java

/**
 * testGetMethod05()/*w w w . j a  v a  2 s  .com*/
 * <br><br>
 *
 * ()
 * <br>
 * F
 * <br><br>
 * () va:not null<br>
 *         () paramClass:{Object.class,<br>
 *                 ValidatorAction.class,<br>
 *                 Field.class,<br>
 *                 ValidationErrors.class}<br>
 *         () va.getName:"requiredXXXXX"<br>
 *
 * <br>
 * () Method:new FieldChecks()#validateRequired<br>
 *
 * <br>
 * va??????5???
 * ?validate??????
 * ?????????????
 * <br>
 *
 * @throws Exception ?????
 */
@Test
public void testGetMethod05() throws Exception {
    // ??
    va.setName("requiredXXXXX");
    @SuppressWarnings("rawtypes")
    Class[] paramClass = { Object.class, ValidatorAction.class, Field.class, ValidationErrors.class };

    // 
    Method result = new FieldChecks().getMethod(va, paramClass);

    // 
    assertEquals(FieldChecks.class, result.getDeclaringClass());
    assertEquals("validateRequired", result.getName());
}

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

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

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

    assertEquals("Authorization", data.indexToName().get(0).iterator().next());
    assertEquals("id", data.indexToName().get(1).iterator().next());
    assertEquals("amount", data.indexToName().get(2).iterator().next());
    assertNotNull(data.indexToExpander().get(2));

    assertEquals("{Authorization}", data.template().headers().get("Authorization").iterator().next());
    assertEquals("{amount}", data.template().queries().get("amount").iterator().next());
}

From source file:net.sf.jasperreports.compilers.GroovyEvaluator.java

protected Object functionCall(String methodName, Object[] args) {
    Method functionMethod = functionsUtil.getMethod4Function(methodName);
    if (functionMethod == null) {
        throw new JRRuntimeException(EXCEPTION_MESSAGE_KEY_FUNCTION_NOT_FOUND, new Object[] { methodName });
    }/*from w  ww .jav  a 2 s.  c o m*/

    // we're relying on this, if we'll ever resolve functions to methods 
    // that have different names we need to adapt the code
    assert functionMethod.getName().equals(methodName);

    Class<?> functionClass = functionMethod.getDeclaringClass();
    MetaClass functionMetaClass = DefaultGroovyMethods.getMetaClass(functionClass);

    MethodClosure functionMethodClosure = null;
    if (FunctionSupport.class.isAssignableFrom(functionClass)) {
        // search for an instance method that applies to the arguments
        MetaMethod metaMethod = functionMetaClass.getMetaMethod(methodName, args);
        if (metaMethod != null && metaMethod.isPublic()) {
            @SuppressWarnings("unchecked")
            FunctionSupport functionObject = getFunctionSupport(
                    (Class<? extends FunctionSupport>) functionClass);
            functionMethodClosure = new MethodClosure(functionObject, methodName);

            if (log.isDebugEnabled()) {
                log.debug("found public instance method " + metaMethod + " in class " + functionClass);
            }
        }
    }

    if (functionMethodClosure == null) {
        // searching for a static method that applies to the arguments
        MetaMethod metaMethod = functionMetaClass.getStaticMetaMethod(methodName, args);
        if (metaMethod != null && metaMethod.isPublic()) {
            // creating a static method closure
            functionMethodClosure = new MethodClosure(functionClass, methodName);

            if (log.isDebugEnabled()) {
                log.debug("found public static method " + metaMethod + " in class " + functionClass);
            }
        }
    }

    if (functionMethodClosure == null) {
        // we didn't find a public instance/static method that applies to the arguments
        throw new MissingMethodException(methodName, functionMetaClass.getTheClass(), args);
    }

    // adding the function methods for the name to the list of registered methods.
    // we need to add all the methods with the same name in the beginning because once we add one method 
    // methodMissing might no longer be called.
    // we need to reregister all methods on each new method since we create ExpandoMetaClass from scratch.
    addFunctionClosureMethods(functionMethodClosure, methodName);

    // adding the methods to the evaluator MetaClass so that it doesn't go again into methodMissing
    ExpandoMetaClass extendedMetaClass = new ExpandoMetaClass(getClass(), false);
    registerMethods(extendedMetaClass);
    extendedMetaClass.initialize();
    DefaultGroovyMethods.setMetaClass((GroovyObject) this, extendedMetaClass);

    // returning what we have to return
    return functionMethodClosure.call(args);
}

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

public TransactionMethodBinding(Method theMethod, FhirContext theContext, Object theProvider) {
    super(null, theMethod, theContext, theProvider);

    myTransactionParamIndex = -1;//from   ww  w  .j a  v a 2  s .  c om
    int index = 0;
    for (IParameter next : getParameters()) {
        if (next instanceof TransactionParameter) {
            if (myTransactionParamIndex != -1) {
                throw new ConfigurationException("Method '" + theMethod.getName() + "' in type "
                        + theMethod.getDeclaringClass().getCanonicalName()
                        + " has multiple parameters annotated with the @" + TransactionParam.class
                        + " annotation, exactly one is required for @" + Transaction.class + " methods");
            }
            myTransactionParamIndex = index;
            myTransactionParamStyle = ((TransactionParameter) next).getParamStyle();
        }
        index++;
    }

    if (myTransactionParamIndex == -1) {
        throw new ConfigurationException("Method '" + theMethod.getName() + "' in type "
                + theMethod.getDeclaringClass().getCanonicalName()
                + " does not have a parameter annotated with the @" + TransactionParam.class + " annotation");
    }
}

From source file:com.google.gdt.eclipse.designer.uibinder.model.util.UiChildSupport.java

/**
 * @return the names of {@link Method} parameters, not <code>null</code>.
 *///  www .  java 2  s .  com
private String[] getMethodParameterNames(Method reflectionMethod) throws Exception {
    IJavaProject javaProject = m_context.getJavaProject();
    IMethod javaMethod = CodeUtils.findMethod(javaProject, reflectionMethod.getDeclaringClass().getName(),
            ReflectionUtils.getMethodSignature(reflectionMethod));
    return javaMethod.getParameterNames();
}

From source file:com.phoenixnap.oss.ramlapisync.parser.SpringMvcResourceParser.java

/**
 * Checks for instances of @Description annotations in 
 * @param method The method to Inspect/* www  .  j  a v a  2  s.c om*/
 * @return a Map of Description and Partial URL Keys
 */
protected Map<String, String> getPathDescriptionsForMethod(Method method) {
    Map<String, String> outDescriptions = new HashMap<>();
    Description description = getAnnotation(method.getDeclaringClass(), Description.class, true);
    if (description != null) {
        for (PathDescription descriptions : description.pathDescriptions()) {
            outDescriptions.put(NamingHelper.cleanLeadingAndTrailingNewLineAndChars(descriptions.key()),
                    descriptions.value());
        }
    }
    if (method.isAnnotationPresent(Description.class)) {
        Description methodDescription = method.getAnnotation(Description.class);
        for (PathDescription descriptions : methodDescription.pathDescriptions()) {
            outDescriptions.put(NamingHelper.cleanLeadingAndTrailingNewLineAndChars(descriptions.key()),
                    descriptions.value());
        }
    }

    return outDescriptions;
}

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

public BaseOutcomeReturningMethodBinding(Method theMethod, FhirContext theContext, Class<?> theMethodAnnotation,
        Object theProvider) {//from www . ja va2 s.  c  om
    super(theMethod, theContext, theProvider);

    if (!theMethod.getReturnType().equals(MethodOutcome.class)) {
        if (!allowVoidReturnType()) {
            throw new ConfigurationException("Method " + theMethod.getName() + " in type "
                    + theMethod.getDeclaringClass().getCanonicalName() + " is a @"
                    + theMethodAnnotation.getSimpleName() + " method but it does not return "
                    + MethodOutcome.class);
        } else if (theMethod.getReturnType() == void.class) {
            myReturnVoid = true;
        }
    }
}

From source file:org.acegisecurity.intercept.method.MethodDefinitionMap.java

protected ConfigAttributeDefinition lookupAttributes(Method method) {
    ConfigAttributeDefinition definition = new ConfigAttributeDefinition();

    // Add attributes explictly defined for this method invocation
    ConfigAttributeDefinition directlyAssigned = (ConfigAttributeDefinition) this.methodMap.get(method);
    merge(definition, directlyAssigned);

    // Add attributes explicitly defined for this method invocation's interfaces
    Class[] interfaces = method.getDeclaringClass().getInterfaces();

    for (int i = 0; i < interfaces.length; i++) {
        Class clazz = interfaces[i];

        try {/*w  w  w .j a v a  2s  .c o m*/
            // Look for the method on the current interface
            Method interfaceMethod = clazz.getDeclaredMethod(method.getName(),
                    (Class[]) method.getParameterTypes());
            ConfigAttributeDefinition interfaceAssigned = (ConfigAttributeDefinition) this.methodMap
                    .get(interfaceMethod);
            merge(definition, interfaceAssigned);
        } catch (Exception e) {
            // skip this interface
        }
    }

    // Return null if empty, as per abstract superclass contract
    if (definition.size() == 0) {
        return null;
    } else {
        return definition;
    }
}