Java Code Examples for org.springframework.util.ClassUtils#getMostSpecificMethod()

The following examples show how to use org.springframework.util.ClassUtils#getMostSpecificMethod() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: AspectJExpressionPointcut.java    From spring-analysis-note with MIT License 6 votes vote down vote up
private ShadowMatch getTargetShadowMatch(Method method, Class<?> targetClass) {
	Method targetMethod = AopUtils.getMostSpecificMethod(method, targetClass);
	if (targetMethod.getDeclaringClass().isInterface()) {
		// Try to build the most specific interface possible for inherited methods to be
		// considered for sub-interface matches as well, in particular for proxy classes.
		// Note: AspectJ is only going to take Method.getDeclaringClass() into account.
		Set<Class<?>> ifcs = ClassUtils.getAllInterfacesForClassAsSet(targetClass);
		if (ifcs.size() > 1) {
			try {
				Class<?> compositeInterface = ClassUtils.createCompositeInterface(
						ClassUtils.toClassArray(ifcs), targetClass.getClassLoader());
				targetMethod = ClassUtils.getMostSpecificMethod(targetMethod, compositeInterface);
			}
			catch (IllegalArgumentException ex) {
				// Implemented interfaces probably expose conflicting method signatures...
				// Proceed with original target method.
			}
		}
	}
	return getShadowMatch(targetMethod, method);
}
 
Example 2
Source File: AbstractFallbackJCacheOperationSource.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
private JCacheOperation<?> computeCacheOperation(Method method, Class<?> targetClass) {
	// Don't allow no-public methods as required.
	if (allowPublicMethodsOnly() && !Modifier.isPublic(method.getModifiers())) {
		return null;
	}

	// The method may be on an interface, but we need attributes from the target class.
	// If the target class is null, the method will be unchanged.
	Method specificMethod = ClassUtils.getMostSpecificMethod(method, targetClass);
	// If we are dealing with method with generic parameters, find the original method.
	specificMethod = BridgeMethodResolver.findBridgedMethod(specificMethod);

	// First try is the method in the target class.
	JCacheOperation<?> operation = findCacheOperation(specificMethod, targetClass);
	if (operation != null) {
		return operation;
	}
	if (specificMethod != method) {
		// Fall back is to look at the original method.
		operation = findCacheOperation(method, targetClass);
		if (operation != null) {
			return operation;
		}
	}
	return null;
}
 
Example 3
Source File: AspectJExpressionPointcut.java    From java-technology-stack with MIT License 6 votes vote down vote up
private ShadowMatch getTargetShadowMatch(Method method, Class<?> targetClass) {
	Method targetMethod = AopUtils.getMostSpecificMethod(method, targetClass);
	if (targetMethod.getDeclaringClass().isInterface()) {
		// Try to build the most specific interface possible for inherited methods to be
		// considered for sub-interface matches as well, in particular for proxy classes.
		// Note: AspectJ is only going to take Method.getDeclaringClass() into account.
		Set<Class<?>> ifcs = ClassUtils.getAllInterfacesForClassAsSet(targetClass);
		if (ifcs.size() > 1) {
			try {
				Class<?> compositeInterface = ClassUtils.createCompositeInterface(
						ClassUtils.toClassArray(ifcs), targetClass.getClassLoader());
				targetMethod = ClassUtils.getMostSpecificMethod(targetMethod, compositeInterface);
			}
			catch (IllegalArgumentException ex) {
				// Implemented interfaces probably expose conflicting method signatures...
				// Proceed with original target method.
			}
		}
	}
	return getShadowMatch(targetMethod, method);
}
 
Example 4
Source File: TransactionalAdvice.java    From alfresco-mvc with Apache License 2.0 6 votes vote down vote up
public Object invoke(final MethodInvocation invocation) throws Throwable {
	Class<?> targetClass = invocation.getThis() != null ? invocation.getThis().getClass() : null;

	Method specificMethod = ClassUtils.getMostSpecificMethod(invocation.getMethod(), targetClass);
	// If we are dealing with method with generic parameters, find the original
	// method.
	specificMethod = BridgeMethodResolver.findBridgedMethod(specificMethod);
	AlfrescoTransaction alfrescoTransaction = parseAnnotation(specificMethod);

	if (alfrescoTransaction != null) {
		RetryingTransactionCallback<Object> exampleWork = new RetryingTransactionCallback<Object>() {
			public Object execute() throws Throwable {
				return invocation.proceed();
			}
		};
		boolean readonly = alfrescoTransaction.readOnly();
		Propagation propagation = alfrescoTransaction.propagation();

		boolean requiresNew = Propagation.REQUIRES_NEW.equals(propagation);
		return serviceRegistry.getRetryingTransactionHelper().doInTransaction(exampleWork, readonly, requiresNew);
	} else {
		return invocation.proceed();
	}

}
 
Example 5
Source File: UiEventListenerMethodAdapter.java    From cuba with Apache License 2.0 6 votes vote down vote up
public UiEventListenerMethodAdapter(Object instance, Class<?> targetClass, Method method, Events events) {
    checkNotNullArgument(targetClass);
    checkNotNullArgument(method);
    checkNotNullArgument(instance);
    checkNotNullArgument(events);

    Method targetMethod = ClassUtils.getMostSpecificMethod(method, targetClass);
    EventListener ann = AnnotatedElementUtils.findMergedAnnotation(targetMethod, EventListener.class);

    if (ann == null) {
        throw new IllegalArgumentException("No @EventListener annotation for method " + method);
    }

    this.instanceRef = new WeakReference<>(instance);
    this.method = method;
    this.bridgedMethod = BridgeMethodResolver.findBridgedMethod(method);
    this.events = events;

    this.declaredEventTypes = resolveDeclaredEventTypes(method, ann);
    if (!ann.condition().isEmpty()) {
        throw new UnsupportedOperationException("@EventListener condition is not supported for UiEvents");
    }
    this.order = resolveOrder(method);
}
 
Example 6
Source File: ApiBootDataSourceSwitchAnnotationInterceptor.java    From api-boot with Apache License 2.0 6 votes vote down vote up
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
    Object methodResult;
    try {
        Class<?> targetClass = (invocation.getThis() != null ? AopUtils.getTargetClass(invocation.getThis()) : null);
        Method specificMethod = ClassUtils.getMostSpecificMethod(invocation.getMethod(), targetClass);
        Method userDeclaredMethod = BridgeMethodResolver.findBridgedMethod(specificMethod);
        // get class declared DataSourceSwitch annotation
        DataSourceSwitch dataSourceSwitch = targetClass.getDeclaredAnnotation(DataSourceSwitch.class);
        if (dataSourceSwitch == null) {
            // get declared DataSourceSwitch annotation
            dataSourceSwitch = userDeclaredMethod.getDeclaredAnnotation(DataSourceSwitch.class);
        }
        if (dataSourceSwitch != null) {
            // setting current thread use data source pool name
            DataSourceContextHolder.set(dataSourceSwitch.value());
        }
        methodResult = invocation.proceed();
    } finally {
        // remove current thread use datasource pool name
        DataSourceContextHolder.remove();
    }
    return methodResult;

}
 
Example 7
Source File: ZebraRoutingPointcut.java    From Zebra with Apache License 2.0 5 votes vote down vote up
boolean match(Method method, Class<?> targetClass) {
	// origin
	if (doMatch(method, targetClass)) {
		return true;
	}
	// cglib
	Class<?> userClass = ClassUtils.getUserClass(targetClass);
	Method specificMethod = ClassUtils.getMostSpecificMethod(method, userClass);
	specificMethod = BridgeMethodResolver.findBridgedMethod(specificMethod);
	if (!specificMethod.equals(method)) {
		if (doMatch(specificMethod, userClass)) {
			return true;
		}
	}
	// jdk proxy
	if (Proxy.isProxyClass(targetClass)) {
		Class<?>[] interfaces = targetClass.getInterfaces();
		for (Class<?> interfaceClass : interfaces) {
			Method interfaceMethod = ClassUtils.getMethodIfAvailable(interfaceClass, method.getName(),
			      method.getParameterTypes());
			if (interfaceMethod != null && doMatch(interfaceMethod, interfaceClass)) {
				return true;
			}
		}
	}
	return false;
}
 
Example 8
Source File: AbstractFallbackCacheOperationSource.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
private Collection<CacheOperation> computeCacheOperations(Method method, Class<?> targetClass) {
	// Don't allow no-public methods as required.
	if (allowPublicMethodsOnly() && !Modifier.isPublic(method.getModifiers())) {
		return null;
	}

	// The method may be on an interface, but we need attributes from the target class.
	// If the target class is null, the method will be unchanged.
	Method specificMethod = ClassUtils.getMostSpecificMethod(method, targetClass);
	// If we are dealing with method with generic parameters, find the original method.
	specificMethod = BridgeMethodResolver.findBridgedMethod(specificMethod);

	// First try is the method in the target class.
	Collection<CacheOperation> opDef = findCacheOperations(specificMethod);
	if (opDef != null) {
		return opDef;
	}

	// Second try is the caching operation on the target class.
	opDef = findCacheOperations(specificMethod.getDeclaringClass());
	if (opDef != null) {
		return opDef;
	}

	if (specificMethod != method) {
		// Fall back is to look at the original method.
		opDef = findCacheOperations(method);
		if (opDef != null) {
			return opDef;
		}
		// Last fall back is the class of the original method.
		return findCacheOperations(method.getDeclaringClass());
	}
	return null;
}
 
Example 9
Source File: AbstractFallbackCacheOperationSource.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
private Collection<CacheOperation> computeCacheOperations(Method method, Class<?> targetClass) {
	// Don't allow no-public methods as required.
	if (allowPublicMethodsOnly() && !Modifier.isPublic(method.getModifiers())) {
		return null;
	}

	// The method may be on an interface, but we need attributes from the target class.
	// If the target class is null, the method will be unchanged.
	Method specificMethod = ClassUtils.getMostSpecificMethod(method, targetClass);
	// If we are dealing with method with generic parameters, find the original method.
	specificMethod = BridgeMethodResolver.findBridgedMethod(specificMethod);

	// First try is the method in the target class.
	Collection<CacheOperation> opDef = findCacheOperations(specificMethod);
	if (opDef != null) {
		return opDef;
	}

	// Second try is the caching operation on the target class.
	opDef = findCacheOperations(specificMethod.getDeclaringClass());
	if (opDef != null && ClassUtils.isUserLevelMethod(method)) {
		return opDef;
	}

	if (specificMethod != method) {
		// Fallback is to look at the original method.
		opDef = findCacheOperations(method);
		if (opDef != null) {
			return opDef;
		}
		// Last fallback is the class of the original method.
		opDef = findCacheOperations(method.getDeclaringClass());
		if (opDef != null && ClassUtils.isUserLevelMethod(method)) {
			return opDef;
		}
	}

	return null;
}
 
Example 10
Source File: ApplicationListenerMethodAdapter.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
public ApplicationListenerMethodAdapter(String beanName, Class<?> targetClass, Method method) {
	this.beanName = beanName;
	this.method = method;
	this.targetClass = targetClass;
	this.bridgedMethod = BridgeMethodResolver.findBridgedMethod(method);

	Method targetMethod = ClassUtils.getMostSpecificMethod(method, targetClass);
	EventListener ann = AnnotatedElementUtils.findMergedAnnotation(targetMethod, EventListener.class);

	this.declaredEventTypes = resolveDeclaredEventTypes(method, ann);
	this.condition = (ann != null ? ann.condition() : null);
	this.order = resolveOrder(method);

	this.methodKey = new AnnotatedElementKey(method, targetClass);
}
 
Example 11
Source File: RunAsAdvice.java    From alfresco-mvc with Apache License 2.0 5 votes vote down vote up
public Object invoke(final MethodInvocation invocation) throws Throwable {

		Class<?> targetClass = invocation.getThis() != null ? invocation.getThis().getClass() : null;

		Method specificMethod = ClassUtils.getMostSpecificMethod(invocation.getMethod(), targetClass);
		// If we are dealing with method with generic parameters, find the original
		// method.
		specificMethod = BridgeMethodResolver.findBridgedMethod(specificMethod);
		AlfrescoRunAs alfrescounRunAs = parseRunAsAnnotation(specificMethod);
		if (alfrescounRunAs != null) {
			String runAs = alfrescounRunAs.value();
			if (StringUtils.hasText(runAs)) {
				RunAsWork<Object> getUserNameRunAsWork = new RunAsWork<Object>() {
					public Object doWork() throws Exception {
						try {
							return invocation.proceed();
						} catch (Throwable e) {
							throw new Exception(e.getMessage(), e);
						}
					}
				};
				return AuthenticationUtil.runAs(getUserNameRunAsWork, runAs);
			}
		}

		return invocation.proceed();
	}
 
Example 12
Source File: FixUseSupperClassFallbackCacheOperationSource.java    From hsweb-framework with Apache License 2.0 4 votes vote down vote up
private Collection<CacheOperation> computeCacheOperations(Method method, Class<?> targetClass) {
    // Don't allow no-public methods as required.
    if (allowPublicMethodsOnly() && !Modifier.isPublic(method.getModifiers())) {
        return null;
    }

    // The method may be on an interface, but we need attributes from the target class.
    // If the target class is null, the method will be unchanged.
    Method specificMethod = ClassUtils.getMostSpecificMethod(method, targetClass);
    // If we are dealing with method with generic parameters, find the original method.
    specificMethod = BridgeMethodResolver.findBridgedMethod(specificMethod);


    // First try is the method in the target class.
    // 解决@CacheConfig不能继承的问题
    Collection<CacheOperation> opDef = findCacheOperations(targetClass, specificMethod);
    if (opDef != null) {
        return opDef;
    }

    // Second try is the caching operation on the target class.
    opDef = findCacheOperations(specificMethod.getDeclaringClass());
    if (opDef != null && ClassUtils.isUserLevelMethod(method)) {
        return opDef;
    }

    if (specificMethod != method) {
        // Fallback is to look at the original method.
        opDef = findCacheOperations(targetClass, method);
        if (opDef != null) {
            return opDef;
        }
        // Last fallback is the class of the original method.
        opDef = findCacheOperations(method.getDeclaringClass());
        if (opDef != null && ClassUtils.isUserLevelMethod(method)) {
            return opDef;
        }
    }

    return null;
}
 
Example 13
Source File: Knife4jController.java    From yshopmall with Apache License 2.0 4 votes vote down vote up
private void initGlobalRequestMappingArray(SwaggerExt swaggerExt) {
    if (this.globalHandlerMappings.size() == 0) {
        String parentPath = "";
        if (!StringUtils.isEmpty(swaggerExt.getBasePath()) && !"/".equals(swaggerExt.getBasePath())) {
            parentPath = parentPath + swaggerExt.getBasePath();
        }

        try {
            List<RequestHandler> requestHandlers = FluentIterable.from(this.handlerProviders).transformAndConcat(this.handlers()).toList();
            Iterator<RequestHandler> var4 = requestHandlers.iterator();

            while(true) {
                RequestHandler requestHandler;
                do {
                    if (!var4.hasNext()) {
                        return;
                    }

                    requestHandler = var4.next();
                } while(!(requestHandler instanceof WebMvcRequestHandler));

                WebMvcRequestHandler webMvcRequestHandler = (WebMvcRequestHandler)requestHandler;
                Set<String> patterns = webMvcRequestHandler.getRequestMapping().getPatternsCondition().getPatterns();
                Set<RequestMethod> restMethods = webMvcRequestHandler.getRequestMapping().getMethodsCondition().getMethods();
                HandlerMethod handlerMethod = webMvcRequestHandler.getHandlerMethod();
                Class<?> controllerClazz = ClassUtils.getUserClass(handlerMethod.getBeanType());
                Method method = ClassUtils.getMostSpecificMethod(handlerMethod.getMethod(), controllerClazz);

                String url;
                for(Iterator<String> var12 = patterns.iterator(); var12.hasNext(); this.globalHandlerMappings.add(new RestHandlerMapping(parentPath + url, controllerClazz, method, restMethods))) {
                    url = var12.next();
                    if (LOGGER.isDebugEnabled()) {
                        LOGGER.debug("url:" + url + "\r\nclass:" + controllerClazz.toString() + "\r\nmethod:" + method.toString());
                    }
                }
            }
        } catch (Exception var14) {
            LOGGER.error(var14.getMessage(), var14);
        }
    }

}
 
Example 14
Source File: AuthenticationAdvice.java    From alfresco-mvc with Apache License 2.0 4 votes vote down vote up
public Object invoke(final MethodInvocation invocation) throws Throwable {

		Class<?> targetClass = invocation.getThis() != null ? invocation.getThis().getClass() : null;

		Method specificMethod = ClassUtils.getMostSpecificMethod(invocation.getMethod(), targetClass);
		// If we are dealing with method with generic parameters, find the original
		// method.
		specificMethod = BridgeMethodResolver.findBridgedMethod(specificMethod);

		AlfrescoAuthentication alfrescoAuthentication = parseAnnotation(specificMethod);

		if (alfrescoAuthentication != null) {

			AuthenticationType authenticationType = alfrescoAuthentication.value();

			if (authenticationType != null && !AuthenticationType.NONE.equals(authenticationType)) {
				AuthenticationService authenticationService = serviceRegistry.getAuthenticationService();
				AuthorityService authorityService = serviceRegistry.getAuthorityService();

				String ticket = authenticationService.getCurrentTicket();
				if (StringUtils.hasText(ticket)) {
					if (AuthenticationType.USER.equals(authenticationType) && authorityService.hasGuestAuthority()) {
						throw new AuthenticationException(
								"User has guest authority where at least a user authentication is required.");
					} else if (AuthenticationType.ADMIN.equals(authenticationType)
							&& !authorityService.hasAdminAuthority()) {
						throw new AuthenticationException(
								"User does not have admin authority where at least named admin authentication is required .");
					}
				} else if (AuthenticationType.GUEST.equals(authenticationType)
						&& authenticationService.guestUserAuthenticationAllowed()) {
					authenticationService.authenticateAsGuest();
				} else {
					throw new AuthenticationException("\nUnable to authenticate due to one of the following reasons:\n"
							+ "Credentials are not provided in HTTP request where at least named user or admin authentication is required.\n"
							+ "Guest user authentication is not allowed where at least guest authentication is required.\n");
				}
			}
		}

		return invocation.proceed();
	}
 
Example 15
Source File: AopTools.java    From api-boot with Apache License 2.0 3 votes vote down vote up
/**
 * get method declared annotation
 *
 * @param targetClass     class instance
 * @param method          method instance
 * @param annotationClass annotation class
 * @param <T>             annotation type
 * @return annotation instance
 */
public static <T> T getMethodAnnotation(Class targetClass, Method method, Class annotationClass) {
    Method specificMethod = ClassUtils.getMostSpecificMethod(method, targetClass);
    // declared method object instance
    Method declaredMethod = BridgeMethodResolver.findBridgedMethod(specificMethod);
    return (T) declaredMethod.getDeclaredAnnotation(annotationClass);
}
 
Example 16
Source File: AopUtils.java    From java-technology-stack with MIT License 3 votes vote down vote up
/**
 * Given a method, which may come from an interface, and a target class used
 * in the current AOP invocation, find the corresponding target method if there
 * is one. E.g. the method may be {@code IFoo.bar()} and the target class
 * may be {@code DefaultFoo}. In this case, the method may be
 * {@code DefaultFoo.bar()}. This enables attributes on that method to be found.
 * <p><b>NOTE:</b> In contrast to {@link org.springframework.util.ClassUtils#getMostSpecificMethod},
 * this method resolves Java 5 bridge methods in order to retrieve attributes
 * from the <i>original</i> method definition.
 * @param method the method to be invoked, which may come from an interface
 * @param targetClass the target class for the current invocation.
 * May be {@code null} or may not even implement the method.
 * @return the specific target method, or the original method if the
 * {@code targetClass} doesn't implement it or is {@code null}
 * @see org.springframework.util.ClassUtils#getMostSpecificMethod
 */
public static Method getMostSpecificMethod(Method method, @Nullable Class<?> targetClass) {
	Class<?> specificTargetClass = (targetClass != null ? ClassUtils.getUserClass(targetClass) : null);
	Method resolvedMethod = ClassUtils.getMostSpecificMethod(method, specificTargetClass);
	// If we are dealing with method with generic parameters, find the original method.
	return BridgeMethodResolver.findBridgedMethod(resolvedMethod);
}
 
Example 17
Source File: AopUtils.java    From spring-analysis-note with MIT License 3 votes vote down vote up
/**
 * Given a method, which may come from an interface, and a target class used
 * in the current AOP invocation, find the corresponding target method if there
 * is one. E.g. the method may be {@code IFoo.bar()} and the target class
 * may be {@code DefaultFoo}. In this case, the method may be
 * {@code DefaultFoo.bar()}. This enables attributes on that method to be found.
 * <p><b>NOTE:</b> In contrast to {@link org.springframework.util.ClassUtils#getMostSpecificMethod},
 * this method resolves Java 5 bridge methods in order to retrieve attributes
 * from the <i>original</i> method definition.
 * @param method the method to be invoked, which may come from an interface
 * @param targetClass the target class for the current invocation.
 * May be {@code null} or may not even implement the method.
 * @return the specific target method, or the original method if the
 * {@code targetClass} doesn't implement it or is {@code null}
 * @see org.springframework.util.ClassUtils#getMostSpecificMethod
 */
public static Method getMostSpecificMethod(Method method, @Nullable Class<?> targetClass) {
	Class<?> specificTargetClass = (targetClass != null ? ClassUtils.getUserClass(targetClass) : null);
	Method resolvedMethod = ClassUtils.getMostSpecificMethod(method, specificTargetClass);
	// If we are dealing with method with generic parameters, find the original method.
	return BridgeMethodResolver.findBridgedMethod(resolvedMethod);
}
 
Example 18
Source File: CacheAspectSupport.java    From java-technology-stack with MIT License 2 votes vote down vote up
/**
 * Convenience method to return a String representation of this Method
 * for use in logging. Can be overridden in subclasses to provide a
 * different identifier for the given method.
 * @param method the method we're interested in
 * @param targetClass class the method is on
 * @return log message identifying this method
 * @see org.springframework.util.ClassUtils#getQualifiedMethodName
 */
protected String methodIdentification(Method method, Class<?> targetClass) {
	Method specificMethod = ClassUtils.getMostSpecificMethod(method, targetClass);
	return ClassUtils.getQualifiedMethodName(specificMethod);
}
 
Example 19
Source File: CacheAspectSupport.java    From lams with GNU General Public License v2.0 2 votes vote down vote up
/**
 * Convenience method to return a String representation of this Method
 * for use in logging. Can be overridden in subclasses to provide a
 * different identifier for the given method.
 * @param method the method we're interested in
 * @param targetClass class the method is on
 * @return log message identifying this method
 * @see org.springframework.util.ClassUtils#getQualifiedMethodName
 */
protected String methodIdentification(Method method, Class<?> targetClass) {
	Method specificMethod = ClassUtils.getMostSpecificMethod(method, targetClass);
	return ClassUtils.getQualifiedMethodName(specificMethod);
}
 
Example 20
Source File: CacheAspectSupport.java    From spring4-understanding with Apache License 2.0 2 votes vote down vote up
/**
 * Convenience method to return a String representation of this Method
 * for use in logging. Can be overridden in subclasses to provide a
 * different identifier for the given method.
 * @param method the method we're interested in
 * @param targetClass class the method is on
 * @return log message identifying this method
 * @see org.springframework.util.ClassUtils#getQualifiedMethodName
 */
protected String methodIdentification(Method method, Class<?> targetClass) {
	Method specificMethod = ClassUtils.getMostSpecificMethod(method, targetClass);
	return ClassUtils.getQualifiedMethodName(specificMethod);
}