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.cherimojava.data.mongo.entity.EntityUtils.java

/**
 * checks if the given method has a return type which is assignable from the declaring class
 *
 * @return true if the given method return type is assignable from the declaring class, false otherwise
 *//*from   www.  j  av a2  s .com*/
static boolean isAssignableFromClass(Method m) {
    return m.getReturnType().isAssignableFrom(m.getDeclaringClass());
}

From source file:org.apache.axis2.description.java2wsdl.bytecode.ParamNameExtractor.java

/**
 * Retrieves a list of function parameter names from a method. 
 * Returns null if unable to read parameter names (i.e. bytecode not
 * built with debug)./*  ww w  .ja  va2 s.co m*/
 */
public static String[] getParameterNamesFromDebugInfo(Method method) {
    // Don't worry about it if there are no params.
    int numParams = method.getParameterTypes().length;
    if (numParams == 0)
        return null;

    // get declaring class
    Class c = method.getDeclaringClass();

    // Don't worry about it if the class is a Java dynamic proxy
    if (Proxy.isProxyClass(c)) {
        return null;
    }

    try {
        // get a parameter reader
        ParamReader pr = new ParamReader(c);
        // get the parameter names
        return pr.getParameterNames(method);
    } catch (IOException e) {
        // log it and leave
        return null;
    }
}

From source file:org.apache.axis.utils.bytecode.ParamNameExtractor.java

/**
 * Retrieve a list of function parameter names from a method
 * Returns null if unable to read parameter names (i.e. bytecode not
 * built with debug)./*  w w w .  j  a  va 2 s  .  c o m*/
 */
public static String[] getParameterNamesFromDebugInfo(Method method) {
    // Don't worry about it if there are no params.
    int numParams = method.getParameterTypes().length;
    if (numParams == 0)
        return null;

    // get declaring class
    Class c = method.getDeclaringClass();

    // Don't worry about it if the class is a Java dynamic proxy 
    if (Proxy.isProxyClass(c)) {
        return null;
    }

    try {
        // get a parameter reader
        ParamReader pr = new ParamReader(c);
        // get the paramter names
        String[] names = pr.getParameterNames(method);
        return names;
    } catch (IOException e) {
        // log it and leave
        log.info(Messages.getMessage("error00") + ":" + e);
        return null;
    }
}

From source file:com.espertech.esper.event.vaevent.PropertyUtility.java

private static PropertyAccessException getAccessExceptionMethod(Method method, Exception e) {
    Class declaring = method.getDeclaringClass();
    String message = "Failed to invoke method " + method.getName() + " on class "
            + JavaClassHelper.getClassNameFullyQualPretty(declaring) + ": " + e.getMessage();
    throw new PropertyAccessException(message, e);
}

From source file:com.github.cherimojava.data.mongo.entity.EntityUtils.java

/**
 * returns the getter method belonging to the given setter method
 *
 * @param m setter method for which a matching getter method shall be found
 * @return getter method belonging to the given Setter method
 * @throws java.lang.IllegalArgumentException if the given method has no matching adder method
 *//*from w  w  w  .j av  a2  s .  com*/
static Method getGetterFromSetter(Method m) {
    try {
        Method getter = m.getDeclaringClass().getMethod(m.getName().replaceFirst("s", "g"));
        checkArgument(getter.getReturnType().equals(m.getParameterTypes()[0]),
                "You can only declare setter methods if there's a matching getter. Found %s without getter",
                m.getName());
        return getter;
    } catch (NoSuchMethodException e) {
        try {
            // check if there's a is method available
            Method isser = m.getDeclaringClass().getMethod(m.getName().replaceFirst("set", "is"));
            // check that both have boolean as type
            checkArgument(boolean.class.equals(Primitives.unwrap(isser.getReturnType()))
                    && boolean.class.equals(Primitives.unwrap(m.getParameterTypes()[0])));
            return isser;
        } catch (NoSuchMethodException e1) {
            // if neither get nor is can be found throw an exception
            throw new IllegalArgumentException(
                    format("Method %s has no corresponding get/is method", m.getName()));
        }
    }
}

From source file:com.bstek.dorado.core.el.DefaultExpressionHandler.java

protected synchronized static Object createDoradoExpressionUtilsBean(Map<String, Method> utilMethods)
        throws Exception {
    if (doradoExpressionUtilsBean == null) {
        ClassPool pool = ClassPool.getDefault();
        CtClass ctClass = null;/*  ww w  .j a va  2  s.  c om*/
        try {
            ctClass = pool.get(DORADO_EXPRESSION_UTILS_TYPE);
        } catch (Exception e) {
            // do nothing
        }
        if (ctClass == null) {
            ctClass = pool.makeClass(DORADO_EXPRESSION_UTILS_TYPE);
        }
        for (Map.Entry<String, Method> entry : utilMethods.entrySet()) {
            String name = entry.getKey();
            Method method = entry.getValue();
            int methodIndex = ArrayUtils.indexOf(method.getDeclaringClass().getMethods(), method);

            StringBuffer buf = new StringBuffer();
            StringBuffer args = new StringBuffer();
            buf.append("public ").append("Object").append(' ').append(name).append('(');
            Class<?>[] parameterTypes = method.getParameterTypes();
            for (int i = 0; i < parameterTypes.length; i++) {
                if (i > 0) {
                    buf.append(',');
                    args.append(',');
                }
                buf.append("Object").append(' ').append("p" + i);
                args.append("p" + i);
            }
            buf.append(")");
            if (method.getExceptionTypes().length > 0) {
                buf.append(" throws ");
                int i = 0;
                for (Class<?> exceptionType : method.getExceptionTypes()) {
                    if (i > 0)
                        buf.append(',');
                    buf.append(exceptionType.getName());
                    i++;
                }
            }
            buf.append("{\n").append("return Class.forName(\"" + method.getDeclaringClass().getName())
                    .append("\").getMethods()[").append(methodIndex).append("].invoke(null, new Object[]{")
                    .append(args).append("});").append("\n}");
            CtMethod delegator = CtNewMethod.make(buf.toString(), ctClass);
            delegator.setName(name);
            ctClass.addMethod(delegator);
        }
        Class<?> cl = ctClass.toClass();
        doradoExpressionUtilsBean = cl.newInstance();
    }
    return doradoExpressionUtilsBean;
}

From source file:com.espertech.esper.event.vaevent.PropertyUtility.java

public static PropertyAccessException getInvocationTargetException(Method method, InvocationTargetException e) {
    Class declaring = method.getDeclaringClass();
    String message = "Failed to invoke method " + method.getName() + " on class "
            + JavaClassHelper.getClassNameFullyQualPretty(declaring) + ": "
            + e.getTargetException().getMessage();
    throw new PropertyAccessException(message, e);
}

From source file:org.kantega.dogmaticmvc.web.DogmaticMVCHandler.java

public static Class getTestClass(Method method) {
    final TestWith testWith = method.getAnnotation(TestWith.class);
    return testWith != null ? testWith.value() : method.getDeclaringClass();
}

From source file:nl.strohalm.cyclos.utils.ClassHelper.java

/**
 * Find a method annotation on the method or declaring class or in any of it's implemented interfaces
 *///from ww  w. j a  va 2  s .c  o m
public static <A extends Annotation> A findAnnotation(final Method method, final Class<A> type,
        final boolean searchInDeclaringClass) {
    final Class<?> declaringClass = method.getDeclaringClass();
    final List<Class<?>> classes = allImplementedTypes(declaringClass);
    for (final Class<?> c : classes) {
        try {
            final Method m = c.getMethod(method.getName(), method.getParameterTypes());
            final A annotation = m.getAnnotation(type);
            if (annotation != null) {
                return annotation;
            }
        } catch (final Exception e) {
            // Try next one
        }
    }
    // at this point the annotation was not found
    if (searchInDeclaringClass) {
        return findAnnotation(method.getDeclaringClass(), type);
    } else {
        return null;
    }
}

From source file:org.shept.util.BeanUtilsExtended.java

/**
 * Merge the property values of the given source bean into the given target bean.
 * <p>Note: Only not-null values are merged into the given target bean.
 * Note: The source and target classes do not have to match or even be derived
 * from each other, as long as the properties match. Any bean properties that the
 * source bean exposes but the target bean does not will silently be ignored.
 * @param source the source bean//from   w  w w  . jav a 2 s  . c  o m
 * @param target the target bean
 * @param editable the class (or interface) to restrict property setting to
 * @param ignoreProperties array of property names to ignore
 * @throws BeansException if the copying failed
 * @see BeanWrapper
 */
private static void mergeProperties(Object source, Object target, Class<?> editable, String[] ignoreProperties)
        throws BeansException {

    Assert.notNull(source, "Source must not be null");
    Assert.notNull(target, "Target must not be null");

    Class<?> actualEditable = target.getClass();
    if (editable != null) {
        if (!editable.isInstance(target)) {
            throw new IllegalArgumentException("Target class [" + target.getClass().getName()
                    + "] not assignable to Editable class [" + editable.getName() + "]");
        }
        actualEditable = editable;
    }
    PropertyDescriptor[] targetPds = getPropertyDescriptors(actualEditable);
    List<String> ignoreList = (ignoreProperties != null) ? Arrays.asList(ignoreProperties) : null;

    for (PropertyDescriptor targetPd : targetPds) {
        if (targetPd.getWriteMethod() != null
                && (ignoreProperties == null || (!ignoreList.contains(targetPd.getName())))) {
            PropertyDescriptor sourcePd = getPropertyDescriptor(source.getClass(), targetPd.getName());
            if (sourcePd != null && sourcePd.getReadMethod() != null) {
                try {
                    Method readMethod = sourcePd.getReadMethod();
                    if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())) {
                        readMethod.setAccessible(true);
                    }
                    Object value = readMethod.invoke(source);
                    if (value != null) {
                        Method writeMethod = targetPd.getWriteMethod();
                        if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())) {
                            writeMethod.setAccessible(true);
                        }
                        writeMethod.invoke(target, value);
                    }
                } catch (Throwable ex) {
                    throw new FatalBeanException("Could not copy properties from source to target", ex);
                }
            }
        }
    }
}