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.castor.jaxb.reflection.ClassInfoBuilder.java

/**
 * Checks if the Method is describeable.
 * /*w w w.  ja  va 2s.  c  o  m*/
 * @param type
 *            the Class of the Method
 * @param method
 *            the Method to check
 * @return true if the method is describeable
 */
private boolean isDescribeable(final Class<?> type, final Method method) {
    boolean isDescribeable = true;
    Class<?> declaringClass = method.getDeclaringClass();
    if ((declaringClass != null) && !type.equals(declaringClass) && (!declaringClass.isInterface())) {
        isDescribeable = false;
    }
    if (method.isSynthetic()) {
        isDescribeable &= false;
    }
    if (Modifier.isStatic(method.getModifiers())) {
        isDescribeable &= false;
    }
    if (Modifier.isTransient(method.getModifiers())) {
        isDescribeable &= false;
    }
    if (!(javaNaming.isAddMethod(method) || javaNaming.isCreateMethod(method) || javaNaming.isGetMethod(method)
            || javaNaming.isIsMethod(method) || javaNaming.isSetMethod(method))) {
        isDescribeable = false;
    }
    return isDescribeable;
}

From source file:com.edmunds.autotest.NoOpInvocationHandler.java

/**
 * Processes a method invocation on a proxy instance and returns
 * the result.  This method will be invoked on an invocation handler
 * when a method is invoked on a proxy instance that it is
 * associated with./*from   ww  w  .  ja va 2 s.  c  o m*/
 *
 * @param proxy  the proxy instance that the method was invoked on
 * @param method the <code>Method</code> instance corresponding to
 *               the interface method invoked on the proxy instance.  The declaring
 *               class of the <code>Method</code> object will be the interface that
 *               the method was declared in, which may be a superinterface of the
 *               proxy interface that the proxy class inherits the method through.
 * @param args   an array of objects containing the values of the
 *               arguments passed in the method invocation on the proxy instance,
 *               or <code>null</code> if interface method takes no arguments.
 *               Arguments of primitive types are wrapped in instances of the
 *               appropriate primitive wrapper class, such as
 *               <code>java.lang.Integer</code> or <code>java.lang.Boolean</code>.
 * @return the value to return from the method invocation on the
 *         proxy instance.  If the declared return type of the interface
 *         method is a primitive type, then the value returned by
 *         this method must be an instance of the corresponding primitive
 *         wrapper class; otherwise, it must be a type assignable to the
 *         declared return type.  If the value returned by this method is
 *         <code>null</code> and the interface method's return type is
 *         primitive, then a <code>NullPointerException</code> will be
 *         thrown by the method invocation on the proxy instance.  If the
 *         value returned by this method is otherwise not compatible with
 *         the interface method's declared return type as described above,
 *         a <code>ClassCastException</code> will be thrown by the method
 *         invocation on the proxy instance.
 * @throws Throwable the exception to throw from the method
 *                   invocation on the proxy instance.  The exception's type must be
 *                   assignable either to any of the exception types declared in the
 *                   <code>throws</code> clause of the interface method or to the
 *                   unchecked exception types <code>java.lang.RuntimeException</code>
 *                   or <code>java.lang.Error</code>.  If a checked exception is
 *                   thrown by this method that is not assignable to any of the
 *                   exception types declared in the <code>throws</code> clause of
 *                   the interface method, then an
 *                   {@link java.lang.reflect.UndeclaredThrowableException} containing the
 *                   exception that was thrown by this method will be thrown by the
 *                   method invocation on the proxy instance.
 * @see java.lang.reflect.UndeclaredThrowableException
 */
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

    final String name = method.getName();
    if ("equals".equals(name)) {
        return args.length == 1 && proxy == args[0];
    }

    if ("hashCode".equals(name)) {
        return 0;
    }

    if ("toString".equals(name)) {
        return "NoOpInvocationHandler";
    }

    if ("getClass".equals(name)) {
        return method.getDeclaringClass();
    }

    // The following methods are to fix NPEs when using a GUI Debugger.
    if ("isEmpty".equals(name)) {
        return Boolean.TRUE;
    }

    if ("toArray".equals(name)) {
        return ArrayUtils.EMPTY_OBJECT_ARRAY;
    }

    if ("size".equals(name)) {
        return 0;
    }
    // End debugger support

    System.out.println("NoOpInvocationHandler: Missing Proxy Method: " + name);

    return null;
}

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

/**
 * Returns whether the given method is considered to be a DAO base class
 * method./*from www  .ja v  a2 s  .  com*/
 * 
 * @param method
 * @return
 */
private boolean isBaseClassMethod(Method method, Class<?> daoInterface) {

    Assert.notNull(method);

    if (method.getDeclaringClass().isAssignableFrom(getDaoClass())) {
        return true;
    }

    return !method.equals(getBaseClassMethod(method, daoInterface));
}

From source file:com.runwaysdk.controller.URLConfigurationManager.java

public void readController(String uri, String controllerClassName, Element el) {
    ControllerMapping controllerMapping = new ControllerMapping(uri, controllerClassName);

    ArrayList<Method> methods = null;
    try {/*  ww w .  ja v a 2  s  .  c om*/
        Class<?> clazz = LoaderDecorator.load(controllerClassName);
        Class<?> clazzBase = LoaderDecorator.load(controllerClassName + "Base");
        methods = new ArrayList<Method>(Arrays.asList(clazz.getMethods()));
        Iterator<Method> it = methods.iterator();
        while (it.hasNext()) {
            Method m = it.next();
            if (!m.getDeclaringClass().equals(clazz) && !m.getDeclaringClass().equals(clazzBase)) {
                it.remove();
            }
        }
    } catch (Throwable t) {
        String exMsg = "Exception loading controller class [" + controllerClassName + "].";
        throw new RunwayConfigurationException(exMsg, t);
    }

    NodeList actions = el.getChildNodes();
    for (int iAction = 0; iAction < actions.getLength(); ++iAction) {
        Node nodeAct = actions.item(iAction);

        if (nodeAct.getNodeType() == Node.ELEMENT_NODE) {
            Element elAction = (Element) nodeAct;

            String method = elAction.getAttribute("method");
            String actionUrl = elAction.getAttribute("uri");

            boolean didMatch = false;
            for (Method m : methods) {
                if (m.getName().matches(method)) {
                    controllerMapping.add(m.getName(), actionUrl);
                    didMatch = true;
                }
            }

            if (!didMatch) {
                String exMsg = "The method regex [" + method + "] for action [" + actionUrl
                        + "] did not match any methods on the controller class definition ["
                        + controllerClassName + "].";
                throw new RunwayConfigurationException(exMsg);
            }
        }
    }

    mappings.add(controllerMapping);
}

From source file:io.swagger.jaxrs.SynapseReader.java

List<String> getPaths(Method method) {
    if (SynapseEndpointServiceMarker.class.isAssignableFrom(method.getDeclaringClass())) {
        List<String> pathList = new ArrayList<>();
        pathList.add(/* ww  w. j  a v  a  2 s.c om*/
                "/" + method.getDeclaringClass().getName().replaceAll("\\.", "/") + "/" + method.getName());
        return pathList;
    } else {
        return null;
    }
}

From source file:com.sinosoft.one.data.jade.context.JadeInvocationHandler.java

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());
    }/*  w ww. java  2 s .  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);
        int ResultSetProcedureResultCount = 0;
        for (int i = 0; i < args.length; i++) {
            if (args[i].getClass() == ResultSetProcedureResult.class) {
                parameters.put("*rs" + (++ResultSetProcedureResultCount) + "*", args[i]);
            } else if (args[i].getClass() == ProcedureResult[].class) {
                ProcedureResult[] pr = (ProcedureResult[]) args[i];
                for (int j = 0; j < pr.length; j++) {
                    if (pr[j] instanceof ResultSetProcedureResult) {
                        parameters.put("*rs" + (++ResultSetProcedureResultCount) + "*", pr[j]);
                    } else if (pr[j] instanceof OutProcedureResult) {
                        parameters.put(INDEX_NAMES[i + j], pr[j]);
                    }
                }
            } else {
                parameters.put(INDEX_NAMES[i], args[i]);
            }
            Param sqlParam = statemenetMetaData.getSQLParamAt(i);
            if (sqlParam != null) {
                parameters.put(sqlParam.value(), args[i]);
            }
        }
        parameters.put("*rscount*", ResultSetProcedureResultCount);
    }
    // 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:tv.arte.resteventapi.core.presentation.decoration.RestEventApiDecorationProvider.java

/**
 * Retrieve a decoration context related to a given bean
 * /*from  www .jav  a2s . co  m*/
 * @param bean A given bean
 * @return A map with field names as keys and appropriate objects as values
 */
public static Map<String, ?> getBeanDecorationContext(final Object bean) {
    Map<String, Object> decorationContext = new LinkedHashMap<String, Object>();

    //Construct Hateoas self referencing link
    if (hrefedBeansControllerMethodMapping.containsKey(bean.getClass())) {
        Method method = hrefedBeansControllerMethodMapping.get(bean.getClass());
        final Map<String, Object> paramValue = new LinkedHashMap<String, Object>();

        ReflectionUtils.doWithFields(bean.getClass(), new FieldCallback() {
            public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {

                String hrefedValue = field.getAnnotation(HrefedParamField.class).value();

                if (StringUtils.isBlank(hrefedValue)) {
                    hrefedValue = field.getName();
                }

                Object fieldValue = null;
                try {
                    fieldValue = PropertyUtils.getProperty(bean, field.getName());
                } catch (Exception e) {
                    throw new RestEventApiRuntimeException("Unable to access the bean property value.");
                }
                if (fieldValue != null) {
                    paramValue.put(hrefedValue, fieldValue);
                }
            }
        }, new FieldFilter() {
            public boolean matches(Field field) {
                return field.isAnnotationPresent(HrefedParamField.class);
            }
        });

        decorationContext.put(HATEOAS_HREF_KEY, RestEventApiControllerLinkBuilder
                .linkTo(method.getDeclaringClass(), method, paramValue, conversionService));
    }

    return decorationContext;
}

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

@Override
public void initializeTypes(Method theMethod, Class<? extends Collection<?>> theOuterCollectionType,
        Class<? extends Collection<?>> theInnerCollectionType, Class<?> theParameterType) {
    if (theOuterCollectionType != null || theInnerCollectionType != null) {
        throw new ConfigurationException("Method '" + theMethod.getName() + "' in type '"
                + theMethod.getDeclaringClass().getCanonicalName() + "' is annotated with @"
                + Sort.class.getName() + " but can not be of collection type");
    }//from w ww .  ja  v a2s  . c  o  m
    if (!theParameterType.equals(SortSpec.class)) {
        throw new ConfigurationException("Method '" + theMethod.getName() + "' in type '"
                + theMethod.getDeclaringClass().getCanonicalName() + "' is annotated with @"
                + Sort.class.getName() + " but is an invalid type, must be: "
                + SortSpec.class.getCanonicalName());
    }

}

From source file:ch.rasc.extclassgenerator.ModelGenerator.java

private static void createModelBean(ModelBean model, AccessibleObject accessibleObject,
        OutputConfig outputConfig) {//  w  w w . jav a  2  s.  c o m
    Class<?> javaType = null;
    String name = null;
    Class<?> declaringClass = null;

    if (accessibleObject instanceof Field) {
        Field field = (Field) accessibleObject;
        javaType = field.getType();
        name = field.getName();
        declaringClass = field.getDeclaringClass();
    } else if (accessibleObject instanceof Method) {
        Method method = (Method) accessibleObject;

        javaType = method.getReturnType();
        if (javaType.equals(Void.TYPE)) {
            return;
        }

        if (method.getName().startsWith("get")) {
            name = StringUtils.uncapitalize(method.getName().substring(3));
        } else if (method.getName().startsWith("is")) {
            name = StringUtils.uncapitalize(method.getName().substring(2));
        } else {
            name = method.getName();
        }

        declaringClass = method.getDeclaringClass();
    }

    ModelType modelType = null;
    if (model.isAutodetectTypes()) {
        for (ModelType mt : ModelType.values()) {
            if (mt.supports(javaType)) {
                modelType = mt;
                break;
            }
        }
    } else {
        modelType = ModelType.AUTO;
    }

    ModelFieldBean modelFieldBean = null;

    ModelField modelFieldAnnotation = accessibleObject.getAnnotation(ModelField.class);
    if (modelFieldAnnotation != null) {

        if (StringUtils.hasText(modelFieldAnnotation.value())) {
            name = modelFieldAnnotation.value();
        }

        if (StringUtils.hasText(modelFieldAnnotation.customType())) {
            modelFieldBean = new ModelFieldBean(name, modelFieldAnnotation.customType());
        } else {
            ModelType type = null;
            if (modelFieldAnnotation.type() != ModelType.NOT_SPECIFIED) {
                type = modelFieldAnnotation.type();
            } else {
                type = modelType;
            }

            modelFieldBean = new ModelFieldBean(name, type);
        }

        updateModelFieldBean(modelFieldBean, modelFieldAnnotation);
        model.addField(modelFieldBean);
    } else {
        if (modelType != null) {
            modelFieldBean = new ModelFieldBean(name, modelType);
            model.addField(modelFieldBean);
        }
    }

    ModelId modelIdAnnotation = accessibleObject.getAnnotation(ModelId.class);
    if (modelIdAnnotation != null) {
        model.setIdProperty(name);
    }

    ModelClientId modelClientId = accessibleObject.getAnnotation(ModelClientId.class);
    if (modelClientId != null) {
        model.setClientIdProperty(name);
        model.setClientIdPropertyAddToWriter(modelClientId.configureWriter());
    }

    ModelVersion modelVersion = accessibleObject.getAnnotation(ModelVersion.class);
    if (modelVersion != null) {
        model.setVersionProperty(name);
    }

    ModelAssociation modelAssociationAnnotation = accessibleObject.getAnnotation(ModelAssociation.class);
    if (modelAssociationAnnotation != null) {
        model.addAssociation(AbstractAssociation.createAssociation(modelAssociationAnnotation, model, javaType,
                declaringClass, name));
    }

    if (modelFieldBean != null && outputConfig.getIncludeValidation() != IncludeValidation.NONE) {

        Set<ModelValidation> modelValidationAnnotations = AnnotationUtils
                .getRepeatableAnnotation(accessibleObject, ModelValidations.class, ModelValidation.class);
        if (!modelValidationAnnotations.isEmpty()) {
            for (ModelValidation modelValidationAnnotation : modelValidationAnnotations) {
                AbstractValidation modelValidation = AbstractValidation.createValidation(name,
                        modelValidationAnnotation, outputConfig.getIncludeValidation());
                if (modelValidation != null) {
                    model.addValidation(modelValidation);
                }
            }
        } else {
            Annotation[] fieldAnnotations = accessibleObject.getAnnotations();

            for (Annotation fieldAnnotation : fieldAnnotations) {
                AbstractValidation.addValidationToModel(model, modelFieldBean, fieldAnnotation,
                        outputConfig.getIncludeValidation());
            }

            if (accessibleObject instanceof Field) {
                PropertyDescriptor pd = BeanUtils.getPropertyDescriptor(declaringClass, name);
                if (pd != null && pd.getReadMethod() != null) {
                    for (Annotation readMethodAnnotation : pd.getReadMethod().getAnnotations()) {
                        AbstractValidation.addValidationToModel(model, modelFieldBean, readMethodAnnotation,
                                outputConfig.getIncludeValidation());
                    }
                }
            }
        }
    }

}

From source file:org.apache.pig.JVMReuseManager.java

public void registerForStaticDataCleanup(Class<?> clazz) {
    for (Method method : clazz.getMethods()) {
        if (method.isAnnotationPresent(StaticDataCleanup.class)) {
            if (!(Modifier.isStatic(method.getModifiers()) && Modifier.isPublic(method.getModifiers()))) {
                throw new RuntimeException("Method " + method.getName() + " in class " + clazz.getName()
                        + "should be public and static as it is annotated with  ");
            }/*from w  ww  .ja va 2 s.c o m*/
            LOG.debug("Method " + method.getName() + " in class " + method.getDeclaringClass()
                    + " registered for static data cleanup");
            instance.cleanupMethods.add(method);
        }
    }
}