Java Code Examples for java.lang.reflect.Method.getDeclaringClass()

The following are Jave code examples for showing how to use getDeclaringClass() of the java.lang.reflect.Method class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: coherence-sql   File: ReflectionExtractorFactory.java   View Source Code Vote up 8 votes
private <T> ValueExtractor provideExtractorForValue(Class<T> clazz, int target, List<String> chainOfProperties) {
    Class<?> propertyClass = clazz;
    List<ValueExtractor> chainedExtractors = Lists.newArrayList();

    for (String property : chainOfProperties) {
        Class<?> finalPropertyClass = propertyClass;

        Optional<Method> matchingMethod = Stream.of(property,
                "get" + WordUtils.capitalize(property),
                "is" + WordUtils.capitalize(property))
                .map(token -> MethodUtils.getMatchingMethod(finalPropertyClass, token))
                .findFirst();

        Method method = matchingMethod.orElseThrow(
                () -> new InvalidQueryException(
                        String.format("Cannot find appropriate method for property [%s] on class [%s]",
                                property, finalPropertyClass)));

        ReflectionExtractor extractor = new ReflectionExtractor(method.getName());
        chainedExtractors.add(extractor);
        propertyClass = method.getDeclaringClass();
    }

    return new ChainedExtractor(chainedExtractors.toArray(new ValueExtractor[chainedExtractors.size()]));
}
 
Example 2
Project: dubbo2   File: InvokerInvocationHandler.java   View Source Code Vote up 7 votes
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    String methodName = method.getName();
    Class<?>[] parameterTypes = method.getParameterTypes();
    if (method.getDeclaringClass() == Object.class) {
        return method.invoke(invoker, args);
    }
    if ("toString".equals(methodName) && parameterTypes.length == 0) {
        return invoker.toString();
    }
    if ("hashCode".equals(methodName) && parameterTypes.length == 0) {
        return invoker.hashCode();
    }
    if ("equals".equals(methodName) && parameterTypes.length == 1) {
        return invoker.equals(args[0]);
    }
    return invoker.invoke(new RpcInvocation(method, args)).recreate();
}
 
Example 3
Project: jdk8u-jdk   File: StandardMBeanIntrospector.java   View Source Code Vote up 6 votes
static boolean isDefinitelyImmutableInfo(Class<?> implClass) {
    if (!NotificationBroadcaster.class.isAssignableFrom(implClass))
        return true;
    synchronized (definitelyImmutable) {
        Boolean immutable = definitelyImmutable.get(implClass);
        if (immutable == null) {
            final Class<NotificationBroadcasterSupport> nbs =
                    NotificationBroadcasterSupport.class;
            if (nbs.isAssignableFrom(implClass)) {
                try {
                    Method m = implClass.getMethod("getNotificationInfo");
                    immutable = (m.getDeclaringClass() == nbs);
                } catch (Exception e) {
                    // Too bad, we'll say no for now.
                    return false;
                }
            } else
                immutable = false;
            definitelyImmutable.put(implClass, immutable);
        }
        return immutable;
    }
}
 
Example 4
Project: openjdk-jdk10   File: ReflectUtil.java   View Source Code Vote up 6 votes
/**
 * Check if the given method is a method declared in the proxy interface
 * implemented by the given proxy instance.
 *
 * @param proxy a proxy instance
 * @param method an interface method dispatched to a InvocationHandler
 *
 * @throws IllegalArgumentException if the given proxy or method is invalid.
 */
public static void checkProxyMethod(Object proxy, Method method) {
    // check if it is a valid proxy instance
    if (proxy == null || !Proxy.isProxyClass(proxy.getClass())) {
        throw new IllegalArgumentException("Not a Proxy instance");
    }
    if (Modifier.isStatic(method.getModifiers())) {
        throw new IllegalArgumentException("Can't handle static method");
    }

    Class<?> c = method.getDeclaringClass();
    if (c == Object.class) {
        String name = method.getName();
        if (name.equals("hashCode") || name.equals("equals") || name.equals("toString")) {
            return;
        }
    }

    if (isSuperInterface(proxy.getClass(), c)) {
        return;
    }

    // disallow any method not declared in one of the proxy interfaces
    throw new IllegalArgumentException("Can't handle: " + method);
}
 
Example 5
Project: OpenJSharp   File: StandardMBeanIntrospector.java   View Source Code Vote up 6 votes
static boolean isDefinitelyImmutableInfo(Class<?> implClass) {
    if (!NotificationBroadcaster.class.isAssignableFrom(implClass))
        return true;
    synchronized (definitelyImmutable) {
        Boolean immutable = definitelyImmutable.get(implClass);
        if (immutable == null) {
            final Class<NotificationBroadcasterSupport> nbs =
                    NotificationBroadcasterSupport.class;
            if (nbs.isAssignableFrom(implClass)) {
                try {
                    Method m = implClass.getMethod("getNotificationInfo");
                    immutable = (m.getDeclaringClass() == nbs);
                } catch (Exception e) {
                    // Too bad, we'll say no for now.
                    return false;
                }
            } else
                immutable = false;
            definitelyImmutable.put(implClass, immutable);
        }
        return immutable;
    }
}
 
Example 6
Project: dubbocloud   File: PojoUtils.java   View Source Code Vote up 6 votes
@SuppressWarnings("unchecked")
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    if (method.getDeclaringClass() == Object.class) {
        return method.invoke(map, args);
    }
    String methodName = method.getName();
    Object value = null;
    if (methodName.length() > 3 && methodName.startsWith("get")) {
        value = map.get(methodName.substring(3, 4).toLowerCase() + methodName.substring(4));
    } else if (methodName.length() > 2 && methodName.startsWith("is")) {
        value = map.get(methodName.substring(2, 3).toLowerCase() + methodName.substring(3));
    } else {
        value = map.get(methodName.substring(0, 1).toLowerCase() + methodName.substring(1));
    }
    if (value instanceof Map<?,?> && ! Map.class.isAssignableFrom(method.getReturnType())) {
        value = realize0((Map<String, Object>) value, method.getReturnType(), null, new IdentityHashMap<Object, Object>());
    }
    return value;
}
 
Example 7
Project: dubbox-hystrix   File: InvokerInvocationHandler.java   View Source Code Vote up 6 votes
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    String methodName = method.getName();
    Class<?>[] parameterTypes = method.getParameterTypes();
    if (method.getDeclaringClass() == Object.class) {
        return method.invoke(invoker, args);
    }
    if ("toString".equals(methodName) && parameterTypes.length == 0) {
        return invoker.toString();
    }
    if ("hashCode".equals(methodName) && parameterTypes.length == 0) {
        return invoker.hashCode();
    }
    if ("equals".equals(methodName) && parameterTypes.length == 1) {
        return invoker.equals(args[0]);
    }
    return invoker.invoke(new RpcInvocation(method, args)).recreate();
}
 
Example 8
Project: OpenJSharp   File: MethodFinder.java   View Source Code Vote up 6 votes
/**
 * Finds method that is accessible from public class or interface through class hierarchy.
 *
 * @param method  object that represents found method
 * @return object that represents accessible method
 * @throws NoSuchMethodException if method is not accessible or is not found
 *                               in specified superclass or interface
 */
public static Method findAccessibleMethod(Method method) throws NoSuchMethodException {
    Class<?> type = method.getDeclaringClass();
    if (Modifier.isPublic(type.getModifiers()) && isPackageAccessible(type)) {
        return method;
    }
    if (Modifier.isStatic(method.getModifiers())) {
        throw new NoSuchMethodException("Method '" + method.getName() + "' is not accessible");
    }
    for (Type generic : type.getGenericInterfaces()) {
        try {
            return findAccessibleMethod(method, generic);
        }
        catch (NoSuchMethodException exception) {
            // try to find in superclass or another interface
        }
    }
    return findAccessibleMethod(method, type.getGenericSuperclass());
}
 
Example 9
Project: OpenJSharp   File: LocatableAnnotation.java   View Source Code Vote up 6 votes
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    try {
        if(method.getDeclaringClass()==Locatable.class)
            return method.invoke(this,args);
        if(Modifier.isStatic(method.getModifiers()))
            // malicious code can pass in a static Method object.
            // doing method.invoke() would end up executing it,
            // so we need to protect against it.
            throw new IllegalArgumentException();

        return method.invoke(core,args);
    } catch (InvocationTargetException e) {
        if(e.getTargetException()!=null)
            throw e.getTargetException();
        throw e;
    }
}
 
Example 10
Project: openjdk-jdk10   File: RuntimeModeler.java   View Source Code Vote up 5 votes
private boolean isWebMethod(Method method) {
    int modifiers = method.getModifiers();
    if (Modifier.isStatic(modifiers) || Modifier.isFinal(modifiers))
        return false;

    Class clazz = method.getDeclaringClass();
    boolean declHasWebService = getAnnotation(clazz, WebService.class) != null;
    WebMethod webMethod = getAnnotation(method, WebMethod.class);
    if (webMethod != null && !webMethod.exclude() && declHasWebService)
        return true;
    return declHasWebService && !classUsesWebMethod.contains(clazz);
}
 
Example 11
Project: openjdk-jdk10   File: MethodUtil.java   View Source Code Vote up 5 votes
private static void ensureInvocableMethod(Method m)
        throws InvocationTargetException {
    Class<?> clazz = m.getDeclaringClass();
    if (clazz.equals(AccessController.class) ||
            clazz.equals(Method.class) ||
            clazz.getName().startsWith("java.lang.invoke."))
        throw new InvocationTargetException(
                new UnsupportedOperationException("invocation not supported"));
}
 
Example 12
Project: lemon   File: ProxyTaskScheduler.java   View Source Code Vote up 5 votes
public String findRunnableKey(Runnable runnable) {
    logger.info("findRunnableKey : {}", runnable);

    if (runnable instanceof ScheduledMethodRunnable) {
        ScheduledMethodRunnable scheduledMethodRunnable = (ScheduledMethodRunnable) runnable;
        Method method = scheduledMethodRunnable.getMethod();
        Class clz = method.getDeclaringClass();

        logger.info("{}.{}", clz.getCanonicalName(), method.getName());

        return clz.getCanonicalName() + "." + method.getName();
    } else {
        return runnable.toString();
    }
}
 
Example 13
Project: OpenJSharp   File: MemberName.java   View Source Code Vote up 5 votes
@SuppressWarnings("LeakingThisInConstructor")
public MemberName(Method m, boolean wantSpecial) {
    m.getClass();  // NPE check
    // fill in vmtarget, vmindex while we have m in hand:
    MethodHandleNatives.init(this, m);
    if (clazz == null) {  // MHN.init failed
        if (m.getDeclaringClass() == MethodHandle.class &&
            isMethodHandleInvokeName(m.getName())) {
            // The JVM did not reify this signature-polymorphic instance.
            // Need a special case here.
            // See comments on MethodHandleNatives.linkMethod.
            MethodType type = MethodType.methodType(m.getReturnType(), m.getParameterTypes());
            int flags = flagsMods(IS_METHOD, m.getModifiers(), REF_invokeVirtual);
            init(MethodHandle.class, m.getName(), type, flags);
            if (isMethodHandleInvoke())
                return;
        }
        throw new LinkageError(m.toString());
    }
    assert(isResolved() && this.clazz != null);
    this.name = m.getName();
    if (this.type == null)
        this.type = new Object[] { m.getReturnType(), m.getParameterTypes() };
    if (wantSpecial) {
        if (isAbstract())
            throw new AbstractMethodError(this.toString());
        if (getReferenceKind() == REF_invokeVirtual)
            changeReferenceKind(REF_invokeSpecial, REF_invokeVirtual);
        else if (getReferenceKind() == REF_invokeInterface)
            // invokeSpecial on a default method
            changeReferenceKind(REF_invokeSpecial, REF_invokeInterface);
    }
}
 
Example 14
Project: jdk8u-jdk   File: MethodUtil.java   View Source Code Vote up 5 votes
private static void ensureInvocableMethod(Method m)
    throws InvocationTargetException
{
    Class<?> clazz = m.getDeclaringClass();
    if (clazz.equals(AccessController.class) ||
        clazz.equals(Method.class) ||
        clazz.getName().startsWith("java.lang.invoke."))
        throw new InvocationTargetException(
            new UnsupportedOperationException("invocation not supported"));
}
 
Example 15
Project: OpenJSharp   File: RuntimeModeler.java   View Source Code Vote up 5 votes
private boolean isWebMethod(Method method) {
    int modifiers = method.getModifiers();
    if (Modifier.isStatic(modifiers) || Modifier.isFinal(modifiers))
        return false;

    Class clazz = method.getDeclaringClass();
    boolean declHasWebService = getAnnotation(clazz, WebService.class) != null;
    WebMethod webMethod = getAnnotation(method, WebMethod.class);
    if (webMethod != null && !webMethod.exclude() && declHasWebService)
        return true;
    return declHasWebService && !classUsesWebMethod.contains(clazz);
}
 
Example 16
Project: OpenJSharp   File: PropertyDescriptor.java   View Source Code Vote up 5 votes
private boolean isAssignable(Method m1, Method m2) {
    if (m1 == null) {
        return true; // choose second method
    }
    if (m2 == null) {
        return false; // choose first method
    }
    if (!m1.getName().equals(m2.getName())) {
        return true; // choose second method by default
    }
    Class<?> type1 = m1.getDeclaringClass();
    Class<?> type2 = m2.getDeclaringClass();
    if (!type1.isAssignableFrom(type2)) {
        return false; // choose first method: it declared later
    }
    type1 = getReturnType(getClass0(), m1);
    type2 = getReturnType(getClass0(), m2);
    if (!type1.isAssignableFrom(type2)) {
        return false; // choose first method: it overrides return type
    }
    Class<?>[] args1 = getParameterTypes(getClass0(), m1);
    Class<?>[] args2 = getParameterTypes(getClass0(), m2);
    if (args1.length != args2.length) {
        return true; // choose second method by default
    }
    for (int i = 0; i < args1.length; i++) {
        if (!args1[i].isAssignableFrom(args2[i])) {
            return false; // choose first method: it overrides parameter
        }
    }
    return true; // choose second method
}
 
Example 17
Project: incubator-netbeans   File: JavaRefactoringGlobalAction.java   View Source Code Vote up 5 votes
private boolean isMethodOverridden(NodeAction d, String name) {
    try {
        Method m = d.getClass().getMethod(name, new Class[0]);

        return m.getDeclaringClass() != CallableSystemAction.class;
    } catch (java.lang.NoSuchMethodException ex) {
        ex.printStackTrace();
        throw new IllegalStateException("Error searching for method " + name + " in " + d); // NOI18N
    }
}
 
Example 18
Project: wamp2spring   File: InvocableHandlerMethod.java   View Source Code Vote up 5 votes
/**
 * Assert that the target bean class is an instance of the class where the given
 * method is declared. In some cases the actual endpoint instance at request-
 * processing time may be a JDK dynamic proxy (lazy initialization, prototype beans,
 * and others). Endpoint classes that require proxying should prefer class-based proxy
 * mechanisms.
 */
private void assertTargetBean(Method method, Object targetBean, Object[] args) {
	Class<?> methodDeclaringClass = method.getDeclaringClass();
	Class<?> targetBeanClass = targetBean.getClass();
	if (!methodDeclaringClass.isAssignableFrom(targetBeanClass)) {
		String text = "The mapped handler method class '"
				+ methodDeclaringClass.getName()
				+ "' is not an instance of the actual endpoint bean class '"
				+ targetBeanClass.getName() + "'. If the endpoint requires proxying "
				+ "(e.g. due to @Transactional), please use class-based proxying.";
		throw new IllegalStateException(getInvocationErrorMessage(text, args));
	}
}
 
Example 19
Project: openjdk-jdk10   File: MethodUtil.java   View Source Code Vote up 5 votes
private static void ensureInvocableMethod(Method m)
        throws InvocationTargetException {
    Class<?> clazz = m.getDeclaringClass();
    if (clazz.equals(AccessController.class) ||
            clazz.equals(Method.class) ||
            clazz.getName().startsWith("java.lang.invoke."))
        throw new InvocationTargetException(
                new UnsupportedOperationException("invocation not supported"));
}
 
Example 20
Project: vertx-zero   File: EventExtractor.java   View Source Code Vote up 4 votes
/**
 * Scan for single
 *
 * @param method
 * @param root
 * @return
 */
private Event extract(final Method method, final String root) {
    // 1.Method path
    final Event event = new Event();
    // 2.Method resolve
    final HttpMethod httpMethod = MethodResolver.resolve(method);
    if (null == httpMethod) {
        // Ignored the method could not be annotated.
        return null;
    } else {
        event.setMethod(httpMethod);
    }
    {
        // 3.1. Get path from method
        final Path path = ZeroHelper.getPath(method);
        if (null == path) {
            // 3.2. Check root double check
            if (!StringUtil.isNil(root)) {
                // Use root directly.
                event.setPath(root);
            }
        } else {
            final String result = PathResolver.resolve(
                    path, root);
            event.setPath(result);
        }
    }
    // 4.Action
    event.setAction(method);
    // 6.Mime resolve
    event.setConsumes(MediaResolver.consumes(method));
    event.setProduces(MediaResolver.produces(method));
    // 7. Instance clazz for proxy
    final Class<?> clazz = method.getDeclaringClass();
    final Object proxy;
    if (clazz.isInterface()) {
        final Class<?> implClass = Instance.uniqueChild(clazz);
        if (null != implClass) {
            proxy = Instance.singleton(implClass);
        } else {
            /**
             * SPEC5: Interface only, direct api, in this situation,
             * The proxy is null and the agent do nothing. The request will
             * send to event bus direct. It's not needed to set
             * implementation class.
             */
            proxy = Virtual.create();
        }
    } else {
        proxy = Instance.singleton(method.getDeclaringClass());
    }
    event.setProxy(proxy);
    return event;
}