Example usage for java.lang.reflect Method getClass

List of usage examples for java.lang.reflect Method getClass

Introduction

In this page you can find the example usage for java.lang.reflect Method getClass.

Prototype

@HotSpotIntrinsicCandidate
public final native Class<?> getClass();

Source Link

Document

Returns the runtime class of this Object .

Usage

From source file:org.audit4j.integration.spring.AuditAdvice.java

/**
 * {@inheritDoc}//from w w  w  .  j ava 2  s  . co m
 * 
 * @see org.springframework.aop.MethodBeforeAdvice#before(java.lang.reflect.Method, java.lang.Object[], java.lang.Object)
 *
 */
@Override
public void before(final Method method, final Object[] params, final Object arg2) throws Throwable {
    AuditManager manager = AuditManager.getInstance();
    manager.audit(method.getClass(), method, params);
}

From source file:com.khs.sherpa.servlet.SherpaRequest.java

private Object[] getParams(Method method) {
    RequestMapper map = new RequestMapper();
    map.setService(service);/*from   ww  w  . j a v  a 2 s .  c om*/
    map.setRequest(servletRequest);
    map.setResponse(servletResponse);

    Class<?>[] types = method.getParameterTypes();
    Object[] params = null;
    // get parameters
    if (types.length > 0) {
        params = new Object[types.length];
    }

    Annotation[][] parameters = method.getParameterAnnotations();
    for (int i = 0; i < parameters.length; i++) {
        Class<?> type = types[i];
        Annotation annotation = null;
        if (parameters[i].length > 0) {
            for (Annotation an : parameters[i]) {
                if (an.annotationType().isAssignableFrom(Param.class)) {
                    annotation = an;
                    break;
                }
            }

        }
        params[i] = map.map(method.getClass().getName(), method.getName(), type, annotation);
    }
    return params;
}

From source file:com.khs.sherpa.servlet.request.DefaultSherpaRequest.java

private Object[] getParams(Method method) {
    RequestMapper map = new RequestMapper();
    map.setApplicationContext(applicationContext);
    map.setRequest(request);/*  w w  w.  ja va2 s  . c o  m*/
    map.setResponse(response);
    map.setRequestProcessor(requestProcessor);
    Class<?>[] types = method.getParameterTypes();
    Object[] params = null;
    // get parameters
    if (types.length > 0) {
        params = new Object[types.length];
    }

    Annotation[][] parameters = method.getParameterAnnotations();
    for (int i = 0; i < parameters.length; i++) {
        Class<?> type = types[i];
        Annotation annotation = null;
        if (parameters[i].length > 0) {
            for (Annotation an : parameters[i]) {
                if (an.annotationType().isAssignableFrom(Param.class)) {
                    annotation = an;
                    break;
                }
            }

        }
        params[i] = map.map(method.getClass().getName(), method.getName(), type, annotation);
    }
    return params;
}

From source file:org.apache.ojb.broker.metadata.ClassDescriptor.java

/**
 * sets the initialization method for this descriptor
 *//*from  ww  w .ja  v  a  2  s.c o m*/
private synchronized void setInitializationMethod(Method newMethod) {
    if (newMethod != null) {
        // make sure it's a no argument method
        if (newMethod.getParameterTypes().length > 0) {
            throw new MetadataException("Initialization methods must be zero argument methods: "
                    + newMethod.getClass().getName() + "." + newMethod.getName());
        }

        // make it accessible if it's not already
        if (!newMethod.isAccessible()) {
            newMethod.setAccessible(true);
        }
    }
    this.initializationMethod = newMethod;
}

From source file:org.apache.ojb.broker.metadata.ClassDescriptor.java

/**
 * Specify the method to instantiate objects
 * represented by this descriptor.//from   w  w w .j a v  a  2 s .  com
 * @see #setFactoryClass 
 */
private synchronized void setFactoryMethod(Method newMethod) {
    if (newMethod != null) {
        // make sure it's a no argument method
        if (newMethod.getParameterTypes().length > 0) {
            throw new MetadataException("Factory methods must be zero argument methods: "
                    + newMethod.getClass().getName() + "." + newMethod.getName());
        }

        // make it accessible if it's not already
        if (!newMethod.isAccessible()) {
            newMethod.setAccessible(true);
        }
    }

    this.factoryMethod = newMethod;
}

From source file:org.apache.sling.commons.proxy.impl.to.InvokedTOFactory.java

/**
 * Instantiates a new InvokedTO Object. This object will contain the
 * relevant invocation properties for the method invocation
 * //from  w ww.java 2  s. co m
 * @param proxy
 *            the proxy object
 * @param method
 *            the invoked method
 * @param args
 *            the method arguments
 * @return the invocation TO
 */
public static InvokedTO newInstance(final Object proxy, final Method method, final Object[] args) {

    final MethodType mt = MethodType.getMethodType(method);
    if (mt.equals(MethodType.BackingResource) || mt.equals(MethodType.Equals) || mt.equals(MethodType.HashCode)
            || mt.equals(MethodType.ToString)) {
        return new BaseInvokedTO(method, "", mt);
    } else if (Annotations.methodHasAnnotation(method, SlingReference.class)) {
        final SlingReference sr = method.getAnnotation(SlingReference.class);

        final String path = StringUtils.trim(sr.path());

        return new BaseInvokedTO(method, path, mt);
    } else if (Annotations.methodHasAnnotation(method, SlingChildren.class)) {
        final SlingChildren sc = method.getAnnotation(SlingChildren.class);
        final String path = StringUtils.trim(sc.path());
        final Class<?> returnType = sc.returnType();

        return new InvokedChildrenTO(method, args, path, returnType, mt);
    } else {
        final SlingProperty sp = method.getAnnotation(SlingProperty.class);
        if (sp == null) {
            throw new java.lang.IllegalStateException("Method " + method.getName() + " on class "
                    + method.getClass().getCanonicalName() + " does not have required annotations");
        }

        final String path = StringUtils.trim(sp.path());
        final String name = StringUtils.trim(sp.name());

        String property = (path.length() > 0 ? path + "/" : path) + name;
        if ((property == null) || (property.length() < 1)) {
            property = MethodType.getBeanName(mt, method);
            property = property.replace("_", ":");
        }
        if ((property == null) || (property.length() < 1)) {
            final String msg = "Could not determine Bean Property name either from @SlingProperty annotation or the JavaBean method name.";
            throw new IllegalStateException(msg);
        }

        return new InvokedPropertyTO(method, args, path, name, mt);
    }

}

From source file:org.mc4j.ems.impl.jmx.connection.support.providers.proxy.GenericMBeanServerProxy.java

private static Method getInterfaceMethod(Method method) {
    Class<?>[] interfaceClasses = method.getClass().getInterfaces();
    for (int i = 0, interfaceClassesLength = interfaceClasses.length; i < interfaceClassesLength; i++) {
        Class interfaceClass = interfaceClasses[i];
        try {/* w  w  w  . j a va  2 s .co  m*/
            return interfaceClass.getMethod(method.getName(), method.getParameterTypes());
        } catch (NoSuchMethodException e) {
            // ignore
        } catch (SecurityException e) {
            // ignore
        }
    }
    // Return null to indicate we were unable to find an interface method.
    return null;
}

From source file:org.springframework.security.web.authentication.preauth.websphere.DefaultWASUsernameAndGroupsExtractor.java

private static Object invokeMethod(Method method, Object instance, Object... args) {
    try {//  w w  w .ja v  a 2 s  .c om
        return method.invoke(instance, args);
    } catch (IllegalArgumentException e) {
        logger.error("Error while invoking method " + method.getClass().getName() + "." + method.getName() + "("
                + Arrays.asList(args) + ")", e);
        throw new RuntimeException("Error while invoking method " + method.getClass().getName() + "."
                + method.getName() + "(" + Arrays.asList(args) + ")", e);
    } catch (IllegalAccessException e) {
        logger.error("Error while invoking method " + method.getClass().getName() + "." + method.getName() + "("
                + Arrays.asList(args) + ")", e);
        throw new RuntimeException("Error while invoking method " + method.getClass().getName() + "."
                + method.getName() + "(" + Arrays.asList(args) + ")", e);
    } catch (InvocationTargetException e) {
        logger.error("Error while invoking method " + method.getClass().getName() + "." + method.getName() + "("
                + Arrays.asList(args) + ")", e);
        throw new RuntimeException("Error while invoking method " + method.getClass().getName() + "."
                + method.getName() + "(" + Arrays.asList(args) + ")", e);
    }
}

From source file:org.unitils.inject.util.InjectionUtils.java

/**
 * Performs auto-injection on a setter by type of the objectToInject into the given target object or targetClass,
 * depending on the value of isStatic. The object is injected to one single setter, if there is more than one
 * candidate setter, a {@link UnitilsException} is thrown. We try to inject the object on the most specific type,
 * this means that when there are muliple setters for one of the super-types or implemented interfaces of the setter
 * type, the one that is lowest in the hierarchy is chosen (if possible, otherwise, a {@link UnitilsException} is
 * thrown./*from w  w  w .java2  s  . com*/
 *
 * @param objectToInject     The object that is injected
 * @param objectToInjectType The type of the object that is injected
 * @param target             The target object (only used when isStatic is false)
 * @param targetClass        The target class (only used when isStatis is true)
 * @param isStatic           Indicates wether injection should be performed on the target object or on the target class
 * @return The object that was replaced by the injection
 */
private static Object injectIntoSetterByType(Object objectToInject, Type objectToInjectType, Object target,
        Class<?> targetClass, boolean isStatic) {
    // Try to find a method with an exact matching type
    Method setterToInjectTo = null;
    Set<Method> settersWithExactType = getSettersOfType(targetClass, objectToInjectType, isStatic);
    if (settersWithExactType.size() > 1) {
        throw new UnitilsException("More than one " + (isStatic ? "static " : "") + "setter with type "
                + objectToInjectType + " found in " + targetClass.getSimpleName());

    } else if (settersWithExactType.size() == 1) {
        setterToInjectTo = settersWithExactType.iterator().next();

    } else {
        // Try to find a supertype setter:
        // If one setter exist that has a type which is more specific than all other setters of the given type,
        // this one is taken. Otherwise, an exception is thrown
        Set<Method> settersOfType = getSettersAssignableFrom(targetClass, objectToInjectType, isStatic);
        if (settersOfType.size() == 0) {
            throw new UnitilsException("No " + (isStatic ? "static " : "") + "setter with (super)type "
                    + objectToInjectType + " found in " + targetClass.getSimpleName());
        }
        for (Method setter : settersOfType) {
            boolean moreSpecific = true;
            for (Method compareToSetter : settersOfType) {
                if (setter != compareToSetter) {
                    if (setter.getClass().isAssignableFrom(compareToSetter.getClass())) {
                        moreSpecific = false;
                        break;
                    }
                }
            }
            if (moreSpecific) {
                setterToInjectTo = setter;
                break;
            }
        }
        if (setterToInjectTo == null) {
            throw new UnitilsException("Multiple candidate target " + (isStatic ? "static " : "")
                    + "setters found in " + targetClass.getSimpleName()
                    + ", with none of them more specific than all others.");
        }
    }

    // Setter to inject into found, inject the object and return old value
    Object oldValue = null;
    try {
        Method getter = getGetter(setterToInjectTo, isStatic);
        if (getter == null) {
            logger.warn("Unable to retrieve current value of field to inject into, no getter found for setter: "
                    + setterToInjectTo + ". Will not be able to restore value after injection.");
        } else {
            oldValue = invokeMethod(target, getter);
        }
    } catch (Exception e) {
        logger.warn(
                "Unable to retrieve current value of field to inject into. Will not be able to restore value after injection.",
                e);
    }

    try {
        invokeMethod(target, setterToInjectTo, objectToInject);

    } catch (InvocationTargetException e) {
        throw new UnitilsException("Unable to inject to setter, exception thrown by target.", e);
    }
    return oldValue;
}