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.apache.ibatis.plugin.Plugin.java

public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    try {//from w  ww. j a  v a2s.co m
        Set<Method> methods = signatureMap.get(method.getDeclaringClass());
        if (methods != null && methods.contains(method)) {
            return interceptor.intercept(new Invocation(target, method, args));
        }
        return method.invoke(target, args);
    } catch (Exception e) {
        throw ExceptionUtil.unwrapThrowable(e);
    }
}

From source file:com.justcloud.osgifier.servlet.OsgifierServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String path = buildUrl(req);/* w w w .  ja  v a2s  .com*/
    Map<String, ?> params = new HashMap<String, Object>();

    Map<String, String> resultMap = new HashMap<String, String>();

    try {
        params = deserializer.deserialize(req.getReader());
        if ("/login".equals(path)) {
            SessionService sessionService = (SessionService) findInstance(SessionServiceImpl.class);
            User user = sessionService.login((String) params.get("username"), (String) params.get("password"));
            resultMap.put("outcome", "success");
            req.getSession().setAttribute("user", user);
            if (user != null) {
                resultMap.put("result", serializer.deepSerialize(user));
            }
        } else if ("/logout".equals(path)) {
            req.getSession().removeAttribute("user");
            req.getSession().invalidate();
            resultMap.put("outcome", "success");
        } else {
            Method m = findRestMethod(RESTMethod.POST, path);
            @SuppressWarnings("unchecked")
            Service instance = findInstance((Class<? extends Service>) m.getDeclaringClass());
            Object args[] = new Object[m.getParameterTypes().length];

            int i = 0;

            for (Annotation[] annotations : m.getParameterAnnotations()) {
                RESTParam restAnnotation = null;

                for (Annotation a : annotations) {
                    if (a.annotationType() == RESTParam.class) {
                        restAnnotation = (RESTParam) a;
                        break;
                    }
                }
                if (restAnnotation == null) {
                    throw new RuntimeException("REST method has non REST annotated parameter");
                }
                Class<?> targetClass = m.getParameterTypes()[i];
                Object value;
                if (restAnnotation.session()) {
                    value = convert(req.getSession().getAttribute(restAnnotation.value()), targetClass);
                } else {
                    value = convert(params.get(restAnnotation.value()), targetClass);
                }
                if (value == null) {
                    throw new RuntimeException(
                            "Parameter " + restAnnotation.value() + " not found in request for " + path);
                }
                args[i++] = value;
            }

            Object result = m.invoke(instance, args);
            resultMap.put("outcome", "success");
            if (result != null) {
                resultMap.put("result", serializer.deepSerialize(result));
            }
        }

    } catch (Exception e) {
        Throwable t = e;
        if (e instanceof InvocationTargetException) {
            t = e.getCause();
        }
        StringWriter stringWriter = new StringWriter();
        PrintWriter writer = new PrintWriter(stringWriter);

        t.printStackTrace(writer);

        resultMap.put("outcome", "error");
        resultMap.put("message", t.getMessage());
        resultMap.put("type", t.getClass().getCanonicalName());
        resultMap.put("stacktrace", stringWriter.getBuffer().toString());
    }

    resp.setContentType("application/json");
    resp.setCharacterEncoding("UTF-8");

    serializer.deepSerialize(resultMap, resp.getWriter());
}

From source file:com.justcloud.osgifier.servlet.OsgifierServlet.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String path = buildUrl(req);/*ww  w.  j  av  a  2s  .  c  o  m*/

    resp.setContentType("application/json");
    resp.setCharacterEncoding("UTF-8");

    if ("/list".equals(path)) {
        List<String> names = new ArrayList<String>();
        try {
            for (Class<? extends Service> sc : serviceClasses) {

                Method m;

                m = sc.getMethod("getName");
                @SuppressWarnings("unchecked")
                Service instance = findInstance((Class<? extends Service>) m.getDeclaringClass());
                String result = instance.getName();

                names.add(result);

            }
            serializer.deepSerialize(names, resp.getWriter());
        } catch (Exception e) {
            Map<String, String> resultMap = new HashMap<String, String>();
            Throwable t = e;
            if (e instanceof InvocationTargetException) {
                t = e.getCause();
            }
            StringWriter stringWriter = new StringWriter();
            PrintWriter writer = new PrintWriter(stringWriter);

            t.printStackTrace(writer);

            resultMap.put("outcome", "error");
            resultMap.put("message", t.getMessage());
            resultMap.put("type", t.getClass().getCanonicalName());
            resultMap.put("stacktrace", stringWriter.getBuffer().toString());

            serializer.deepSerialize(resultMap, resp.getWriter());
        }
    } else {
        Method m = findRestMethod(RESTMethod.GET, path);
        @SuppressWarnings("unchecked")
        Service instance = findInstance((Class<? extends Service>) m.getDeclaringClass());
        try {
            Object result = m.invoke(instance);

            serializer.deepSerialize(result, resp.getWriter());
        } catch (Exception e) {
            Map<String, String> resultMap = new HashMap<String, String>();
            Throwable t = e;
            if (e instanceof InvocationTargetException) {
                t = e.getCause();
            }
            StringWriter stringWriter = new StringWriter();
            PrintWriter writer = new PrintWriter(stringWriter);

            t.printStackTrace(writer);

            resultMap.put("outcome", "error");
            resultMap.put("message", t.getMessage());
            resultMap.put("type", t.getClass().getCanonicalName());
            resultMap.put("stacktrace", stringWriter.getBuffer().toString());

            serializer.deepSerialize(resultMap, resp.getWriter());
        }
    }

}

From source file:eu.qualityontime.commons.MethodUtils.java

/**
 * <p>/*from  w  w  w  .ja v a2s  . c om*/
 * Return an accessible method (that is, one that can be invoked via
 * reflection) that implements the specified Method. If no such method can
 * be found, return <code>null</code>.
 * </p>
 *
 * @param method
 *            The method that we wish to call
 * @return The accessible method
 */
public static Method getAccessibleMethod(final Method method) {

    // Make sure we have a method to check
    if (method == null) {
        return null;
    }

    return getAccessibleMethod(method.getDeclaringClass(), method);
}

From source file:com.bstek.dorado.view.output.ClientOutputHelper.java

protected Map<String, PropertyConfig> doGetPropertyConfigs(Class<?> beanType) throws Exception {
    beanType = ProxyBeanUtils.getProxyTargetType(beanType);
    Map<String, PropertyConfig> propertyConfigs = new HashMap<String, PropertyConfig>();

    ClientObjectInfo clientObjectInfo = getClientObjectInfo(beanType);
    if (clientObjectInfo != null) {
        for (Map.Entry<String, ClientProperty> entry : clientObjectInfo.getPropertyConfigs().entrySet()) {
            String property = entry.getKey();
            ClientProperty clientProperty = entry.getValue();

            PropertyConfig propertyConfig = new PropertyConfig();
            if (clientProperty.ignored()) {
                propertyConfig.setIgnored(true);
            } else {
                if (StringUtils.isNotEmpty(clientProperty.outputter())) {
                    BeanWrapper beanWrapper = BeanFactoryUtils.getBean(clientProperty.outputter(),
                            Scope.instant);
                    propertyConfig.setOutputter(beanWrapper.getBean());
                }//from  www .  ja  v  a 2s. c  o m

                if (clientProperty.alwaysOutput()) {
                    propertyConfig.setEscapeValue(FAKE_ESCAPE_VALUE);
                } else if (StringUtils.isNotEmpty(clientProperty.escapeValue())) {
                    propertyConfig.setEscapeValue(clientProperty.escapeValue());
                }
            }
            propertyConfigs.put(property, propertyConfig);
        }
    }

    boolean isAssembledComponent = (AssembledComponent.class.isAssignableFrom(beanType));
    Class<?> superComponentType = null;
    if (isAssembledComponent) {
        superComponentType = beanType;
        while (superComponentType != null && AssembledComponent.class.isAssignableFrom(superComponentType)) {
            superComponentType = superComponentType.getSuperclass();
            Assert.notNull(superComponentType);
        }
    }

    for (PropertyDescriptor propertyDescriptor : PropertyUtils.getPropertyDescriptors(beanType)) {
        String property = propertyDescriptor.getName();
        Method readMethod = propertyDescriptor.getReadMethod();
        if (readMethod.getDeclaringClass() != beanType) {
            try {
                readMethod = beanType.getMethod(readMethod.getName(), readMethod.getParameterTypes());
            } catch (NoSuchMethodException e) {
                // do nothing
            }
        }

        TypeInfo typeInfo;
        Class<?> propertyType = propertyDescriptor.getPropertyType();
        if (Collection.class.isAssignableFrom(propertyType)) {
            typeInfo = TypeInfo.parse((ParameterizedType) readMethod.getGenericReturnType(), true);
            if (typeInfo != null) {
                propertyType = typeInfo.getType();
            }
        } else if (propertyType.isArray()) {
            typeInfo = new TypeInfo(propertyType.getComponentType(), true);
        } else {
            typeInfo = new TypeInfo(propertyType, false);
        }

        PropertyConfig propertyConfig = null;
        ClientProperty clientProperty = readMethod.getAnnotation(ClientProperty.class);
        if (clientProperty != null) {
            propertyConfig = new PropertyConfig();
            if (clientProperty.ignored()) {
                propertyConfig.setIgnored(true);
            } else {
                if (StringUtils.isNotEmpty(clientProperty.outputter())) {
                    BeanWrapper beanWrapper = BeanFactoryUtils.getBean(clientProperty.outputter(),
                            Scope.instant);
                    propertyConfig.setOutputter(beanWrapper.getBean());
                } else if (Component.class.isAssignableFrom(propertyType)) {
                    BeanWrapper beanWrapper = BeanFactoryUtils.getBean(COMPONENT_OUTPUTTER, Scope.instant);
                    propertyConfig.setOutputter(beanWrapper.getBean());
                } else if (DataControl.class.isAssignableFrom(propertyType)
                        || FloatControl.class.isAssignableFrom(propertyType)) {
                    BeanWrapper beanWrapper = BeanFactoryUtils.getBean(COMPONENT_OUTPUTTER, Scope.instant);
                    propertyConfig.setOutputter(beanWrapper.getBean());
                } else if (DataType.class.isAssignableFrom(propertyType)) {
                    BeanWrapper beanWrapper = BeanFactoryUtils.getBean(DATA_TYPE_PROPERTY_OUTPUTTER,
                            Scope.instant);
                    propertyConfig.setOutputter(beanWrapper.getBean());
                } else if (Object.class.equals(propertyType)) {
                    BeanWrapper beanWrapper = BeanFactoryUtils.getBean(DATA_OUTPUTTER, Scope.instant);
                    propertyConfig.setOutputter(beanWrapper.getBean());
                } else if (!EntityUtils.isSimpleType(propertyType) && !propertyType.isArray()) {
                    BeanWrapper beanWrapper = BeanFactoryUtils.getBean(OBJECT_OUTPUTTER, Scope.instant);
                    propertyConfig.setOutputter(beanWrapper.getBean());
                }

                if (!clientProperty.evaluateExpression()) {
                    propertyConfig.setEvaluateExpression(false);
                }

                if (clientProperty.alwaysOutput()) {
                    propertyConfig.setEscapeValue(FAKE_ESCAPE_VALUE);
                } else if (StringUtils.isNotEmpty(clientProperty.escapeValue())) {
                    propertyConfig.setEscapeValue(clientProperty.escapeValue());
                }
            }
        } else if (isAssembledComponent && readMethod.getDeclaringClass() == beanType
                && EntityUtils.isSimpleType(propertyType)) {
            if (BeanUtils.getPropertyDescriptor(superComponentType, property) == null) {
                propertyConfig = new PropertyConfig();
                propertyConfig.setIgnored(true);
            }
        }

        ComponentReference componentReference = readMethod.getAnnotation(ComponentReference.class);
        if (componentReference != null && String.class.equals(propertyType)) {
            if (propertyConfig == null) {
                propertyConfig = new PropertyConfig();
            }
            if (propertyConfig.getOutputter() == null) {
                BeanWrapper beanWrapper = BeanFactoryUtils.getBean(COMPONENT_REFERENCE_OUTPUTTER,
                        Scope.instant);
                propertyConfig.setOutputter(beanWrapper.getBean());
            }
        }

        if (!propertyType.isPrimitive() && (Number.class.isAssignableFrom(propertyType)
                || Boolean.class.isAssignableFrom(propertyType))) {
            if (propertyConfig == null) {
                propertyConfig = new PropertyConfig();
            }
            if (propertyConfig.getEscapeValue() == PropertyConfig.NONE_VALUE) {
                propertyConfig.setEscapeValue(null);
            }
        }

        if (propertyConfig != null) {
            propertyConfigs.put(property, propertyConfig);
        }
    }
    return (propertyConfigs.isEmpty()) ? null : propertyConfigs;
}

From source file:com.expressui.core.dao.query.EntityQuery.java

/**
 * Clear this query so that all filters (query parameters) and sort-criteria are removed (except for defaults).
 * The method uses reflection to clear any filters defined as bean properties by subclasses. Once cleared,
 * re-execution of query results in all records being found or a default list of default filters are specified.
 *
 * @see #initializeDefaults/*ww  w  .  j a  v  a2  s  .c  o m*/
 */
public void clear() {
    try {
        for (PropertyDescriptor descriptor : descriptors) {
            Method writeMethod = descriptor.getWriteMethod();
            Method readMethod = descriptor.getReadMethod();
            if (readMethod != null && writeMethod != null
                    && !writeMethod.getDeclaringClass().equals(EntityQuery.class)
                    && !writeMethod.getDeclaringClass().equals(Object.class)) {
                Class type = descriptor.getPropertyType();
                if (type.isPrimitive() && !type.isArray()) {
                    if (ReflectionUtil.isNumberType(type)) {
                        writeMethod.invoke(this, 0);
                    } else if (Boolean.class.isAssignableFrom(type)) {
                        writeMethod.invoke(this, false);
                    }
                } else {
                    writeMethod.invoke(this, new Object[] { null });
                }
            }
        }
    } catch (IllegalAccessException e) {
        Assert.PROGRAMMING.fail(e);
    } catch (InvocationTargetException e) {
        Assert.PROGRAMMING.fail(e);
    }

    initializeDefaults();
}

From source file:at.ac.tuwien.infosys.jcloudscale.test.unit.TestReflectionUtil.java

Method resolveMethod(Class<?> type, String name, Class<?>... paramTypes) {
    Method expected = ReflectionUtils.findMethod(type, name, paramTypes);
    Method actual = null;/*from   www.j  av a 2s . c o  m*/
    try {
        actual = findMethod(type, name, paramTypes);
    } catch (Exception e) {
        // Ignore
    }
    assertEquals(expected, actual);
    if (actual != null) {
        assertEquals(expected.getDeclaringClass(), actual.getDeclaringClass());
    }
    return actual;
}

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

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

    assertEquals("", data.template().url());
    assertEquals("GET", data.template().method());
    assertEquals(MediaType.APPLICATION_JSON_VALUE, data.template().headers().get("Accept").iterator().next());
}

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

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

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

From source file:javadz.beanutils.MethodUtils.java

/**
 * <p>Return an accessible method (that is, one that can be invoked via
 * reflection) that implements the specified Method.  If no such method
 * can be found, return <code>null</code>.</p>
 *
 * @param clazz The class of the object//from w  w w  .  j  a va  2  s.co  m
 * @param method The method that we wish to call
 * @return The accessible method
 * @since 1.8.0
 */
public static Method getAccessibleMethod(Class clazz, Method method) {

    // Make sure we have a method to check
    if (method == null) {
        return (null);
    }

    // If the requested method is not public we cannot call it
    if (!Modifier.isPublic(method.getModifiers())) {
        return (null);
    }

    boolean sameClass = true;
    if (clazz == null) {
        clazz = method.getDeclaringClass();
    } else {
        sameClass = clazz.equals(method.getDeclaringClass());
        if (!method.getDeclaringClass().isAssignableFrom(clazz)) {
            throw new IllegalArgumentException(
                    clazz.getName() + " is not assignable from " + method.getDeclaringClass().getName());
        }
    }

    // If the class is public, we are done
    if (Modifier.isPublic(clazz.getModifiers())) {
        if (!sameClass && !Modifier.isPublic(method.getDeclaringClass().getModifiers())) {
            setMethodAccessible(method); // Default access superclass workaround
        }
        return (method);
    }

    String methodName = method.getName();
    Class[] parameterTypes = method.getParameterTypes();

    // Check the implemented interfaces and subinterfaces
    method = getAccessibleMethodFromInterfaceNest(clazz, methodName, parameterTypes);

    // Check the superclass chain
    if (method == null) {
        method = getAccessibleMethodFromSuperclass(clazz, methodName, parameterTypes);
    }

    return (method);

}