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.espertech.esper.epl.core.MethodPollingViewableFactory.java

/**
 * Creates a method-invocation polling view for use as a stream that calls a method, or pulls results from cache.
 * @param streamNumber the stream number
 * @param methodStreamSpec defines the class and method to call
 * @param eventAdapterService for creating event types and events
 * @param epStatementAgentInstanceHandle for time-based callbacks
 * @param methodResolutionService for resolving classes and imports
 * @param engineImportService for resolving configurations
 * @param schedulingService for scheduling callbacks in expiry-time based caches
 * @param scheduleBucket for schedules within the statement
 * @param exprEvaluatorContext expression evaluation context
 * @return pollable view//from  w  w w. j  a  v a  2s. c  o  m
 * @throws ExprValidationException if the expressions cannot be validated or the method descriptor
 * has incorrect class and method names, or parameter number and types don't match
 */
public static HistoricalEventViewable createPollMethodView(int streamNumber, MethodStreamSpec methodStreamSpec,
        EventAdapterService eventAdapterService, EPStatementAgentInstanceHandle epStatementAgentInstanceHandle,
        MethodResolutionService methodResolutionService, EngineImportService engineImportService,
        SchedulingService schedulingService, ScheduleBucket scheduleBucket,
        ExprEvaluatorContext exprEvaluatorContext) throws ExprValidationException {
    // Try to resolve the method
    FastMethod staticMethod;
    Class declaringClass;
    try {
        Method method = methodResolutionService.resolveMethod(methodStreamSpec.getClassName(),
                methodStreamSpec.getMethodName());
        declaringClass = method.getDeclaringClass();
        FastClass declaringFastClass = FastClass.create(Thread.currentThread().getContextClassLoader(),
                method.getDeclaringClass());
        staticMethod = declaringFastClass.getMethod(method);
    } catch (Exception e) {
        throw new ExprValidationException(e.getMessage());
    }

    // Determine object type returned by method
    Class beanClass = staticMethod.getReturnType();
    if ((beanClass == void.class) || (beanClass == Void.class)
            || (JavaClassHelper.isJavaBuiltinDataType(beanClass))) {
        throw new ExprValidationException("Invalid return type for static method '" + staticMethod.getName()
                + "' of class '" + methodStreamSpec.getClassName() + "', expecting a Java class");
    }
    if (staticMethod.getReturnType().isArray()) {
        beanClass = staticMethod.getReturnType().getComponentType();
    }

    // If the method returns a Map, look up the map type
    Map<String, Object> mapType = null;
    String mapTypeName = null;
    if ((JavaClassHelper.isImplementsInterface(staticMethod.getReturnType(), Map.class))
            || (staticMethod.getReturnType().isArray() && JavaClassHelper
                    .isImplementsInterface(staticMethod.getReturnType().getComponentType(), Map.class))) {
        Method typeGetterMethod = null;
        String getterMethodName = methodStreamSpec.getMethodName() + "Metadata";
        try {
            typeGetterMethod = methodResolutionService.resolveMethod(methodStreamSpec.getClassName(),
                    getterMethodName, new Class[0], new boolean[0], new boolean[0]);
        } catch (Exception e) {
            log.warn("Could not find getter method for Map-typed method invocation, expected a method by name '"
                    + getterMethodName + "' accepting no parameters");
        }
        if ((typeGetterMethod != null)
                && (JavaClassHelper.isImplementsInterface(typeGetterMethod.getReturnType(), Map.class))) {
            Object resultType = null;
            try {
                resultType = typeGetterMethod.invoke(null);
            } catch (Exception e) {
                log.warn("Error invoking getter method for Map-typed method invocation, for method by name '"
                        + getterMethodName + "' accepting no parameters");
            }

            if ((resultType != null) && (resultType instanceof Map)) {
                mapTypeName = methodStreamSpec.getClassName() + "." + typeGetterMethod.getName();
                mapType = (Map<String, Object>) resultType;
            }
        }
    }

    // Determine event type from class and method name
    EventType eventType;
    if (mapType != null) {
        eventType = eventAdapterService.addNestableMapType(mapTypeName, mapType, null, false, true, true, false,
                false);
    } else {
        eventType = eventAdapterService.addBeanType(beanClass.getName(), beanClass, false, true, true);
    }

    // Construct polling strategy as a method invocation
    ConfigurationMethodRef configCache = engineImportService
            .getConfigurationMethodRef(declaringClass.getName());
    if (configCache == null) {
        configCache = engineImportService.getConfigurationMethodRef(declaringClass.getSimpleName());
    }
    ConfigurationDataCache dataCacheDesc = (configCache != null) ? configCache.getDataCacheDesc() : null;
    DataCache dataCache = DataCacheFactory.getDataCache(dataCacheDesc, epStatementAgentInstanceHandle,
            schedulingService, scheduleBucket);
    PollExecStrategy methodPollStrategy = new MethodPollingExecStrategy(eventAdapterService, staticMethod,
            mapTypeName != null, eventType);

    return new MethodPollingViewable(methodStreamSpec, streamNumber, methodStreamSpec.getExpressions(),
            methodPollStrategy, dataCache, eventType, exprEvaluatorContext);
}

From source file:com.kangyonggan.cms.util.Reflections.java

/**
 * ?private/protectedpublic?????JDKSecurityManager
 *//*w w  w . j  a v a  2 s .  com*/
public static void makeAccessible(Method method) {
    boolean temp = (!Modifier.isPublic(method.getModifiers())
            || !Modifier.isPublic(method.getDeclaringClass().getModifiers())) && !method.isAccessible();
    if (temp) {
        method.setAccessible(true);
    }
}

From source file:$.Reflections.java

/**
     * ?private/protectedpublic?????JDKSecurityManager
     *//*from  w  ww .  j ava 2  s .c  o  m*/
    public static void makeAccessible(Method method) {
        if ((!Modifier.isPublic(method.getModifiers())
                || !Modifier.isPublic(method.getDeclaringClass().getModifiers())) && !method.isAccessible()) {
            method.setAccessible(true);
        }
    }

From source file:com.zigbee.framework.common.util.BeanCopyUtil.java

/**
 * ?/* ww  w.  j a  v a2  s  .c  o m*/
 * @author tun.tan
 * @Date 2011-9-29 ?11:18:42
 */
public static void copyProps(Object source, Object target, String[] igonre) {
    Assert.notNull(source, "Source must not be null");
    Assert.notNull(target, "Target must not be null");
    Class<?> actualEditable = target.getClass();
    PropertyDescriptor[] targetPds = getPropertyDescriptors(actualEditable);
    Object methodName = null;
    //      Object targetValue=null;
    //?
    for (PropertyDescriptor targetPd : targetPds) {
        if (targetPd.getWriteMethod() != null) {

            try {
                PropertyDescriptor sourcePd = getPropertyDescriptor(source.getClass(), targetPd.getName());
                if (igonre != null) {
                    boolean jump = false;
                    //
                    for (int i = 0; i < igonre.length; i++) {
                        if (igonre[i] == null) {//
                            continue;
                        }
                        if (targetPd.getName().equals(igonre[i])) {//?
                            logger.info(targetPd.getName());
                            jump = true;
                        }
                    }
                    if (jump) {//
                        continue;
                    }
                }
                if (sourcePd != null && sourcePd.getReadMethod() != null) {//
                    Method readMethod = sourcePd.getReadMethod();
                    if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())) {
                        readMethod.setAccessible(true);
                    }
                    Object value = readMethod.invoke(source);
                    //Check whether the value is empty, only copy the properties which are not empty
                    //                  targetValue=value;
                    if (value != null) {//
                        Method writeMethod = targetPd.getWriteMethod();
                        methodName = writeMethod.getName();
                        if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())) {
                            readMethod.setAccessible(true);
                        }
                        writeMethod.invoke(target, value);
                    }

                }
            } catch (BeansException e) {
                e.printStackTrace();
                String errMsg = "BEAN COPY Exception! methodName=" + methodName + " ;" + e.getMessage();
                logger.error(errMsg);
                throw new ZigbeeSystemException("beanCopyException", errMsg, e.getCause());

            } catch (SecurityException e) {
                e.printStackTrace();
                String errMsg = "BEAN COPY Exception! methodName=" + methodName + " ;" + e.getMessage();
                logger.error(errMsg);
                throw new ZigbeeSystemException("beanCopyException", errMsg, e.getCause());

            } catch (IllegalArgumentException e) {
                e.printStackTrace();
                String errMsg = "BEAN COPY Exception! methodName=" + methodName + " ;" + e.getMessage();
                logger.error(errMsg);
                throw new ZigbeeSystemException("beanCopyException", errMsg, e.getCause());

            } catch (IllegalAccessException e) {
                e.printStackTrace();
                String errMsg = "BEAN COPY Exception! methodName=" + methodName + " ;" + e.getMessage();
                logger.error(errMsg);
                throw new ZigbeeSystemException("beanCopyException", errMsg, e.getCause());

            } catch (InvocationTargetException e) {
                e.printStackTrace();
                String errMsg = "BEAN COPY Exception! methodName=" + methodName + " ;" + e.getMessage();
                logger.error(errMsg);
                throw new ZigbeeSystemException("beanCopyException", errMsg, e.getCause());

            }

        }
    }
}

From source file:com.facebook.stetho.inspector.MethodDispatcher.java

/**
 * Determines if the method is a {@link ChromeDevtoolsMethod}, and validates accordingly
 * if it is./*www  .  j  a  v  a 2  s.co  m*/
 *
 * @throws IllegalArgumentException Thrown if it is a {@link ChromeDevtoolsMethod} but
 *     it otherwise fails to satisfy requirements.
 */
private static boolean isDevtoolsMethod(Method method) throws IllegalArgumentException {
    if (!method.isAnnotationPresent(ChromeDevtoolsMethod.class)) {
        return false;
    } else {
        Class<?> args[] = method.getParameterTypes();
        String methodName = method.getDeclaringClass().getSimpleName() + "." + method.getName();
        Util.throwIfNot(args.length == 2, "%s: expected 2 args, got %s", methodName, args.length);
        Util.throwIfNot(args[0].equals(JsonRpcPeer.class), "%s: expected 1st arg of JsonRpcPeer, got %s",
                methodName, args[0].getName());
        Util.throwIfNot(args[1].equals(JSONObject.class), "%s: expected 2nd arg of JSONObject, got %s",
                methodName, args[1].getName());

        Class<?> returnType = method.getReturnType();
        if (!returnType.equals(void.class)) {
            Util.throwIfNot(JsonRpcResult.class.isAssignableFrom(returnType),
                    "%s: expected JsonRpcResult return type, got %s", methodName, returnType.getName());
        }
        return true;
    }
}

From source file:org.apache.sling.scripting.sightly.impl.compiler.CompileTimeObjectModel.java

private static boolean isMethodAllowed(Method method) {
    Class<?> declaringClass = method.getDeclaringClass();
    //methods of the Object.class are forbidden (except toString, which is allowed)
    return declaringClass != Object.class || TO_STRING_METHOD.equals(method.getName());
}

From source file:com.cnksi.core.tools.utils.Reflections.java

/**
 * ?private/protectedpublic?????JDKSecurityManager
 *///from   w  w w . j  a va  2s.c  o  m
public static void makeAccessible(Method method) {

    if ((!Modifier.isPublic(method.getModifiers())
            || !Modifier.isPublic(method.getDeclaringClass().getModifiers())) && !method.isAccessible()) {
        method.setAccessible(true);
    }
}

From source file:ipc.RPC.java

/** Expert: Make multiple, parallel calls to a set of servers. */
public static Object[] call(Method method, Object[][] params, InetSocketAddress[] addrs, Configuration conf)
        throws IOException, InterruptedException {

    return getProtocolEngine(method.getDeclaringClass(), conf).call(method, params, addrs, conf);
}

From source file:io.dyn.core.handler.Handlers.java

public static <A extends Annotation> A find(Class<A> anno, Method method) {
    if (null == method) {
        return null;
    }//from  w  w  w  .j av a  2 s . c om

    A on = AnnotationUtils.findAnnotation(method, anno);
    if (null != on) {
        return on;
    }

    Class<?>[] implClasses = method.getDeclaringClass().getInterfaces();
    for (Class<?> cl : implClasses) {
        try {
            Method m = cl.getDeclaredMethod(method.getName(), method.getParameterTypes());
            if (null != m) {
                on = find(anno, m);
                if (null != on) {
                    return on;
                }
            }
        } catch (NoSuchMethodException e) {
        }
    }

    return null;
}

From source file:blue.lapis.pore.impl.event.PoreEventImplTest.java

private static boolean isDefault(Method method) {
    // Default methods are public non-abstract instance methods declared in an interface.
    return ((method.getModifiers()
            & (Modifier.ABSTRACT | Modifier.PUBLIC | Modifier.STATIC)) == Modifier.PUBLIC)
            && method.getDeclaringClass().isInterface();
}