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:Main.java

public static void dumpMethod(final Method method) {
    final StringBuilder builder = new StringBuilder();
    builder.append("------------------------------\n");
    builder.append("MethodName: ").append(method.getName()).append("\n");
    builder.append("ParameterTypes:{");
    for (Class<?> cls : method.getParameterTypes()) {
        builder.append(cls.getName()).append(", ");
    }// w  ww .  jav  a2s.c  o m
    builder.append("}\n");
    builder.append("GenericParameterTypes:{");
    for (Type cls : method.getGenericParameterTypes()) {
        builder.append(cls.getClass()).append(", ");
    }
    builder.append("}\n");
    builder.append("TypeParameters:{");
    for (TypeVariable<Method> cls : method.getTypeParameters()) {
        builder.append(cls.getName()).append(", ");
    }
    builder.append("}\n");
    builder.append("DeclaredAnnotations:{");
    for (Annotation cls : method.getDeclaredAnnotations()) {
        builder.append(cls).append(", ");
    }
    builder.append("}\n");
    builder.append("Annotations:{");
    for (Annotation cls : method.getAnnotations()) {
        builder.append(cls).append(", ");
    }
    builder.append("}\n");
    builder.append("ExceptionTypes:{");
    for (Class<?> cls : method.getExceptionTypes()) {
        builder.append(cls.getName()).append(", ");
        ;
    }
    builder.append("}\n");
    builder.append("ReturnType: ").append(method.getReturnType());
    builder.append("\nGenericReturnType: ").append(method.getGenericReturnType());
    builder.append("\nDeclaringClass: ").append(method.getDeclaringClass());
    builder.append("\n");

    System.out.println(builder.toString());
}

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

/**
 * Flip with alterBean is realized only if 'alterBean' property is filled and valid.
 * //from   www  . ja v  a2 s  .c  o m
 * @param pMInvoc
 *            current method invocation
 * @param alterBean
 *            target bean to call
 * @param logger
 *            current logger for the class
 * @return flag if alterBean should be invoked
 */
private boolean shouldCallAlterBeanMethod(final MethodInvocation pMInvoc, String alterBean, Logger logger) {
    boolean callAlterBeanMethod = false;
    Method method = pMInvoc.getMethod();

    String currentBeanName = currentBeanName(pMInvoc);
    if (alterBean != null && !alterBean.isEmpty()) {
        if (alterBean.equals(currentBeanName)) {
            logger.debug("FeatureFlipping on method:{} class:{} already on the alterBean {}", method.getName(),
                    method.getDeclaringClass().getName(), alterBean);
        } else {
            if (!appCtx.containsBean(alterBean)) {
                throw new BeanCreationException("ff4j-aop : bean name '" + alterBean
                        + "' has not been found in applicationContext still declared in 'alterBean' property of bean "
                        + method.getDeclaringClass());
            }
            callAlterBeanMethod = true;
        }
    }
    return callAlterBeanMethod;
}

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

@Override
protected Map<RamlActionType, String> getHttpMethodAndName(Method method) {
    RequestMapping methodMapping = getRequestMapping(method);
    RequestMapping classMapping = getAnnotation(method.getDeclaringClass(), RequestMapping.class, false);
    RestController classRestController = getAnnotation(method.getDeclaringClass(), RestController.class, false);
    Controller classController = getAnnotation(method.getDeclaringClass(), Controller.class, false);

    RequestMethod[] verbs = methodMapping.method();
    if (verbs == null || verbs.length == 0) {
        verbs = RequestMethod.values();/*from ww w. ja  v a 2s  . co  m*/
    }
    String name = "";

    if (classMapping != null && classMapping.value() != null && classMapping.value().length > 0) {
        name += NamingHelper.resolveProperties(classMapping.value()[0]);
    }
    if (classRestController != null && classRestController.value() != null) {
        name += NamingHelper.resolveProperties(classRestController.value());
    }
    if (classController != null && classController.value() != null) {
        name += NamingHelper.resolveProperties(classController.value());
    }

    if (methodMapping.value() != null && methodMapping.value().length > 0) {
        if (name.endsWith("/") && methodMapping.value()[0].startsWith("/")) {
            name = name.substring(0, name.length() - 1);
        } else if (name != "" && !name.endsWith("/") && !methodMapping.value()[0].startsWith("/")) {
            name += "/";
        }
        name += NamingHelper.resolveProperties(methodMapping.value()[0]);
    }

    Map<RamlActionType, String> outMap = new HashMap<>();
    for (RequestMethod rm : verbs) {
        try {
            RamlActionType apiAction = RamlActionType.valueOf(rm.name());
            outMap.put(apiAction, name);
        } catch (Exception ex) {
            // skip verb not supported by RAML
            logger.warn("Skipping unknown verb " + rm);
        }
    }
    return outMap;// TODO sort value out
}

From source file:hu.bme.mit.sette.common.model.snippet.Snippet.java

/**
 * Instantiates a new snippet./*from   www .  ja  va 2 s. c  o m*/
 *
 * @param pContainer
 *            the snippet container
 * @param pMethod
 *            the method
 * @param classLoader
 *            the class loader for loading snippet project classes
 * @throws ValidatorException
 *             if validation has failed
 */
Snippet(final SnippetContainer pContainer, final Method pMethod, final ClassLoader classLoader)
        throws ValidatorException {
    Validate.notNull(pContainer, "The container must not be null");
    Validate.notNull(pMethod, "The method must not be null");
    Validate.isTrue(pContainer.getJavaClass().equals(pMethod.getDeclaringClass()),
            "The method must be declared in the " + "Java class of the container\n"
                    + "(container.javaClass: [%s])\n" + "(method.declaringClass: [%s])",
            pContainer.getJavaClass(), pMethod.getDeclaringClass());

    container = pContainer;
    method = pMethod;
    inputFactory = null; // should be set later by setter method

    // start validation
    MethodValidator v = new MethodValidator(pMethod);
    // modifiers are checked by the container when parsing the Java class

    // check SETTE annotations
    AnnotationMap methodAnnots = SetteAnnotationUtils.getSetteAnnotations(pMethod);

    SetteRequiredStatementCoverage reqStmtCovAnnot;
    SetteIncludeCoverage inclCovAnnot;

    reqStmtCovAnnot = (SetteRequiredStatementCoverage) methodAnnots.get(SetteRequiredStatementCoverage.class);

    inclCovAnnot = (SetteIncludeCoverage) methodAnnots.get(SetteIncludeCoverage.class);

    if (reqStmtCovAnnot == null) {
        v.addException(
                "Method must have the annotation @" + SetteRequiredStatementCoverage.class.getSimpleName());
    }

    if ((inclCovAnnot != null && methodAnnots.size() != 2)
            || (inclCovAnnot == null && methodAnnots.size() != 1)) {
        v.addException("Method must not have any SETTE annotation " + "other than @"
                + SetteRequiredStatementCoverage.class.getName() + " and @"
                + SetteIncludeCoverage.class.getSimpleName());
    }

    // check and parse annotation @SetteRequiredStatementCoverage
    if (reqStmtCovAnnot != null) {
        double value = reqStmtCovAnnot.value();

        if (value < SetteRequiredStatementCoverage.MIN || value > SetteRequiredStatementCoverage.MAX) {
            v.addException(String.format("Required statement coverage must be " + "between %.2f%% and %.2f%%",
                    SetteRequiredStatementCoverage.MIN, SetteRequiredStatementCoverage.MAX));
        }

        requiredStatementCoverage = value;
    } else {
        requiredStatementCoverage = -1;
    }

    // check and parse annotation @SetteIncludeCoverage
    includedConstructors = new HashSet<>();
    includedMethods = new HashSet<>();
    parseIncludedMethods(inclCovAnnot, v, classLoader);

    v.validate();
}

From source file:com.github.erchu.beancp.commons.NameBasedMapConvention.java

@Override
public List<Binding> getBindings(final MappingInfo mappingsInfo, final Class sourceClass,
        final Class destinationClass) {
    List<Binding> result = new LinkedList<>();
    BeanInfo sourceBeanInfo, destinationBeanInfo;

    try {//from w  w  w .j a  v  a  2s  .  com
        destinationBeanInfo = Introspector.getBeanInfo(destinationClass);
    } catch (IntrospectionException ex) {
        throw new MappingException(String.format("Failed to get bean info for %s", destinationClass), ex);
    }

    try {
        sourceBeanInfo = Introspector.getBeanInfo(sourceClass);
    } catch (IntrospectionException ex) {
        throw new MappingException(String.format("Failed to get bean info for %s", sourceClass), ex);
    }

    boolean allDestinationMembersMapped = true;

    for (PropertyDescriptor destinationProperty : destinationBeanInfo.getPropertyDescriptors()) {
        Method destinationMember = destinationProperty.getWriteMethod();

        if (destinationMember != null) {
            BindingSide destinationBindingSide = new PropertyBindingSide(destinationProperty);

            if (isDestinationMemberExpectedToBind(destinationBindingSide) == false) {
                continue;
            }

            List<BindingSide> sourceBindingSide = getMatchingSourceMemberByName(sourceBeanInfo, sourceClass,
                    destinationProperty.getName(), MemberAccessType.PROPERTY);

            if (sourceBindingSide != null) {
                BindingSide[] sourceBindingSideArray = sourceBindingSide.stream().toArray(BindingSide[]::new);

                Binding binding = getBindingIfAvailable(sourceClass, destinationClass, mappingsInfo,
                        sourceBindingSideArray, destinationBindingSide);

                if (binding != null) {
                    result.add(binding);
                }
            } else {
                allDestinationMembersMapped = false;
            }
        }
    }

    for (Field destinationMember : destinationClass.getFields()) {
        BindingSide destinationBindingSide = new FieldBindingSide(destinationMember);

        if (isDestinationMemberExpectedToBind(destinationBindingSide) == false) {
            continue;
        }

        List<BindingSide> sourceBindingSide = getMatchingSourceMemberByName(sourceBeanInfo, sourceClass,
                destinationMember.getName(), MemberAccessType.FIELD);

        if (sourceBindingSide != null) {

            BindingSide[] sourceBindingSideArray = sourceBindingSide.stream().toArray(BindingSide[]::new);

            Binding binding = getBindingIfAvailable(sourceClass, destinationClass, mappingsInfo,
                    sourceBindingSideArray, destinationBindingSide);

            if (binding != null) {
                result.add(binding);
            }
        } else {
            allDestinationMembersMapped = false;
        }
    }

    if (_failIfNotAllDestinationMembersMapped) {
        if (allDestinationMembersMapped == false) {
            throw new MapperConfigurationException(
                    "Not all destination members are mapped." + " This exception has been trown because "
                            + "failIfNotAllDestinationMembersMapped option is enabled.");
        }
    }

    if (_failIfNotAllSourceMembersMapped) {
        boolean allSourceMembersMapped = true;

        for (PropertyDescriptor sourceProperty : sourceBeanInfo.getPropertyDescriptors()) {
            Method sourceMember = sourceProperty.getReadMethod();

            if (sourceMember != null) {
                if (sourceMember.getDeclaringClass().equals(Object.class)) {
                    continue;
                }

                BindingSide sourceBindingSide = new PropertyBindingSide(sourceProperty);

                if (isSourceMemberMapped(result, sourceBindingSide) == false) {
                    allSourceMembersMapped = false;
                    break;
                }
            }
        }

        // if all properties are mapped we still need to check fields
        if (allSourceMembersMapped) {
            for (Field sourceMember : sourceClass.getFields()) {
                if (sourceMember.getDeclaringClass().equals(Object.class)) {
                    continue;
                }

                BindingSide sourceBindingSide = new FieldBindingSide(sourceMember);

                if (isSourceMemberMapped(result, sourceBindingSide) == false) {
                    allSourceMembersMapped = false;
                    break;
                }
            }
        }

        if (allSourceMembersMapped == false) {
            throw new MapperConfigurationException(
                    "Not all source members are mapped." + " This exception has been trown because "
                            + "failIfNotAllSourceMembersMapped option is enabled.");
        }
    }

    return result;
}

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

/**
 * Gets the RequestMapping annotation from the method and any interfaces it might implement
 * //from   w  ww.ja  v  a 2s  .  c  om
 * @param method
 * @return
 */
private RequestMapping getRequestMapping(Method method) {
    RequestMapping requestMapping = method.getAnnotation(RequestMapping.class);
    if (requestMapping == null) {
        for (Class<?> cInterface : method.getDeclaringClass().getInterfaces()) {
            try {
                Method methodInInterface = cInterface.getMethod(method.getName(), method.getParameterTypes());
                requestMapping = methodInInterface.getAnnotation(RequestMapping.class);
                if (requestMapping != null) {
                    return requestMapping;
                }
            } catch (NoSuchMethodException nsme) {
                // Possibly Expected outcome. Not really an error but meh.
            }
        }
    }

    return requestMapping;
}

From source file:de.xaniox.heavyspleef.core.flag.FlagRegistry.java

public void unregister(Class<? extends AbstractFlag<?>> flagClass) {
    String path = null;//w w  w.  ja  v  a  2  s .co m

    for (Entry<DualKeyMap.DualKeyPair<String, Flag>, FlagClassHolder> entry : registeredFlagsMap.entrySet()) {
        FlagClassHolder holder = entry.getValue();

        if (holder.flagClass != flagClass) {
            continue;
        }

        Flag annotation = entry.getKey().getSecondaryKey();
        if (annotation.hasCommands()) {
            CommandManager manager = heavySpleef.getCommandManager();
            manager.unregisterSpleefCommand(flagClass);
        }

        Iterator<Method> methodIterator = queuedInitMethods.iterator();
        while (methodIterator.hasNext()) {
            Method method = methodIterator.next();
            if (method.getDeclaringClass() == flagClass) {
                methodIterator.remove();
            }
        }

        Unregister.Unregisterer.runUnregisterMethods(flagClass, heavySpleef, true, true);
        path = entry.getKey().getPrimaryKey();

        for (Game game : heavySpleef.getGameManager().getGames()) {
            if (!game.isFlagPresent(flagClass)) {
                continue;
            }

            AbstractFlag<?> flag = game.getFlag(flagClass);
            game.removeFlag(flagClass);

            Element element = DocumentHelper.createElement("flag");
            element.addAttribute("name", path);
            flag.marshal(element);

            UnloadedFlag unloaded = new UnloadedFlag();
            unloaded.setXmlElement(element);
            game.addFlag(unloaded, false);
        }
        break;
    }

    if (path != null) {
        registeredFlagsMap.remove(path);
    }
}

From source file:edu.harvard.med.screensaver.model.AbstractEntity.java

/**
 * Determine if a given property should be used in determining equivalence.
 * /* w  w w . j  ava2 s .  c om*/
 * @return boolean (see code, since this is private method)
 * @see #isEquivalent(AbstractEntity)
 */
// TODO: can we annotate a bean's properties with "@equivalence" and do some
// introspection to retrieve these annotated "equivalence" properties, rather
// than relying upon the below heuristics?
private boolean isEquivalenceProperty(PropertyDescriptor property) {
    Method method = property.getReadMethod();
    if (method == null) {
        // this can occur if there is a public setter method, but a non-public
        // getter method
        log.debug("no corresponding getter method for property " + property.getDisplayName());
        return false;
    }
    // only test methods that are declared by subclasses of AbstractEntity
    if (method.getDeclaringClass().equals(AbstractEntity.class)
            || !AbstractEntity.class.isAssignableFrom(method.getDeclaringClass())) {
        return false;
    }
    if (method.getAnnotation(Transient.class) != null) {
        return false;
    }
    if (method.getAnnotation(Column.class) != null
            && method.getAnnotation(Column.class).isNotEquivalenceProperty()) {
        return false;
    }
    // do not check embeddable types (as this would require descending into the embeddable to check equivalence)
    if (property.getPropertyType().getAnnotation(Embeddable.class) != null) {
        return false;
    }

    return !(Collection.class.isAssignableFrom(property.getPropertyType())
            || Map.class.isAssignableFrom(property.getPropertyType())
            || AbstractEntity.class.isAssignableFrom(property.getPropertyType()));
}

From source file:org.javelin.sws.ext.bind.internal.metadata.PropertyCallback.java

/**
 * Like {@link MethodCallback#doWith(Method)}, but for two methods.
 * //  w  ww. j a  v  a 2 s  . com
 * @see org.springframework.util.ReflectionUtils.MethodCallback#doWith(java.lang.reflect.Method)
 */
@Override
public void doWith(Method getter) throws IllegalArgumentException, IllegalAccessException {
    Method setter = ReflectionUtils.findMethod(clazz, getter.getName().replaceFirst("^get", "set"),
            getter.getReturnType());

    if (log.isTraceEnabled()) {
        if (setter != null) {
            log.trace(" - Analyzing pair of methods: {}.{}/{}.{}", getter.getDeclaringClass().getSimpleName(),
                    getter.getName(), setter.getDeclaringClass().getSimpleName(), setter.getName());
        } else {
            // we have java.util.Collection
            log.trace(" - Analyzing method: {}.{}", getter.getDeclaringClass().getSimpleName(),
                    getter.getName());
        }
    }

    // TODO: properly handle class hierarchies
    String propertyName = StringUtils.uncapitalize(getter.getName().substring(3));
    // metadata for getter/setter
    PropertyMetadata<T, ?> metadata = PropertyMetadata.newPropertyMetadata(this.clazz, getter.getReturnType(),
            propertyName, getter, setter, PropertyKind.BEAN);
    this.doWithPropertySafe(metadata);
}

From source file:org.apache.calcite.test.CalciteAssert.java

/** Finds a non-static method based on its target, name and arguments.
 * Throws if not found. *//*w  w  w . ja va2 s.c  o m*/
static Method method(Object o, String methodName, Object[] args) {
    for (Class<?> aClass = o.getClass();;) {
        loop: for (Method method1 : aClass.getMethods()) {
            if (method1.getName().equals(methodName) && method1.getParameterTypes().length == args.length
                    && Modifier.isPublic(method1.getDeclaringClass().getModifiers())) {
                for (Pair<Object, Class> pair : Pair.zip(args, (Class[]) method1.getParameterTypes())) {
                    if (!pair.right.isInstance(pair.left)) {
                        continue loop;
                    }
                }
                return method1;
            }
        }
        if (aClass.getSuperclass() != null && aClass.getSuperclass() != Object.class) {
            aClass = aClass.getSuperclass();
        } else {
            final Class<?>[] interfaces = aClass.getInterfaces();
            if (interfaces.length > 0) {
                aClass = interfaces[0];
            } else {
                break;
            }
        }
    }
    throw new AssertionError("method " + methodName + " not found");
}