当前位置: 首页>>代码示例>>Java>>正文


Java ReflectionUtils类代码示例

本文整理汇总了Java中org.springframework.util.ReflectionUtils的典型用法代码示例。如果您正苦于以下问题:Java ReflectionUtils类的具体用法?Java ReflectionUtils怎么用?Java ReflectionUtils使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


ReflectionUtils类属于org.springframework.util包,在下文中一共展示了ReflectionUtils类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: run

import org.springframework.util.ReflectionUtils; //导入依赖的package包/类
@Override
public Object run() {

    try {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletResponse response = ctx.getResponse();

        if (!rateLimiter.tryAcquire()) {
            HttpStatus httpStatus = HttpStatus.TOO_MANY_REQUESTS;

            response.setContentType(MediaType.TEXT_PLAIN_VALUE);
            response.setStatus(httpStatus.value());
            ctx.setResponseStatusCode(httpStatus.value());
            ctx.setSendZuulResponse(false);
        }
    } catch (Exception e) {
        ReflectionUtils.rethrowRuntimeException(e);
    }
    return null;
}
 
开发者ID:kenly333,项目名称:service-hive,代码行数:21,代码来源:RateLimitZuulFilter.java

示例2: run

import org.springframework.util.ReflectionUtils; //导入依赖的package包/类
@Override
public Object run() {
  try {
    RequestContext currentContext = RequestContext.getCurrentContext();
    HttpServletResponse response = currentContext.getResponse();

    if (!rateLimiter.tryAcquire()) {

      response.setContentType(MediaType.TEXT_PLAIN_VALUE);
      response.setStatus(this.tooManyRequests.value());
      response.getWriter().append(this.tooManyRequests.getReasonPhrase());

      currentContext.setSendZuulResponse(false);

      throw new ZuulException(this.tooManyRequests.getReasonPhrase(),
          this.tooManyRequests.value(),
          this.tooManyRequests.getReasonPhrase());
    }
  } catch (Exception e) {
    ReflectionUtils.rethrowRuntimeException(e);
  }
  return null;
}
 
开发者ID:drm317,项目名称:cloud-native-reference,代码行数:24,代码来源:ThrottlingPreFilter.java

示例3: afterPropertiesSet

import org.springframework.util.ReflectionUtils; //导入依赖的package包/类
@Override
public void afterPropertiesSet() throws Exception {
	String[] beanNames = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(this.applicationContext, Object.class);
	for(String beanName : beanNames){
		Class<?> beanType = this.applicationContext.getType(beanName);
		if(beanType != null){
			final Class<?> userType = ClassUtils.getUserClass(beanType);
			ReflectionUtils.doWithMethods(userType, method -> {
				if(AnnotatedElementUtils.findMergedAnnotation(method, ReactiveSocket.class) != null) {
					ServiceMethodInfo info = new ServiceMethodInfo(method);
					logger.info("Registering remote endpoint at path {}, exchange {} for method {}", info.getMappingInfo().getPath(), info.getMappingInfo().getExchangeMode(), method);
					MethodHandler methodHandler = new MethodHandler(applicationContext.getBean(beanName), info);
					mappingHandlers.add(methodHandler);
				}
			});
		}
	}
	initDefaultConverters();
}
 
开发者ID:viniciusccarvalho,项目名称:spring-cloud-sockets,代码行数:20,代码来源:DispatcherHandler.java

示例4: getAuthor

import org.springframework.util.ReflectionUtils; //导入依赖的package包/类
private Object getAuthor(Event event) {
    if (event == null) {
        return null;
    }
    Class<? extends Event> clazz = event.getClass();
    Method method;
    if (!userAccessors.containsKey(clazz)) {
        method = ReflectionUtils.findMethod(clazz, "getUser");
        if (method == null) {
            method = ReflectionUtils.findMethod(clazz, "getAuthor");
        }
        userAccessors.put(clazz, method);
    } else {
        method = userAccessors.get(clazz);
    }
    if (method != null) {
        Object result = ReflectionUtils.invokeMethod(method, event);
        if (result instanceof User) {
            return result;
        }
    }
    return null;
}
 
开发者ID:GoldRenard,项目名称:JuniperBotJ,代码行数:24,代码来源:SourceResolverServiceImpl.java

示例5: JBossModulesAdapter

import org.springframework.util.ReflectionUtils; //导入依赖的package包/类
public JBossModulesAdapter(ClassLoader loader) {
	this.classLoader = loader;
	try {
		Field transformer = ReflectionUtils.findField(loader.getClass(), "transformer");
		transformer.setAccessible(true);
		this.delegatingTransformer = transformer.get(loader);
		if (!this.delegatingTransformer.getClass().getName().equals(DELEGATING_TRANSFORMER_CLASS_NAME)) {
			throw new IllegalStateException("Transformer not of the expected type DelegatingClassFileTransformer: " +
					this.delegatingTransformer.getClass().getName());
		}
		this.addTransformer = ReflectionUtils.findMethod(this.delegatingTransformer.getClass(),
				"addTransformer", ClassFileTransformer.class);
		this.addTransformer.setAccessible(true);
	}
	catch (Exception ex) {
		throw new IllegalStateException("Could not initialize JBoss 7 LoadTimeWeaver", ex);
	}
}
 
开发者ID:lamsfoundation,项目名称:lams,代码行数:19,代码来源:JBossModulesAdapter.java

示例6: copyPropertiesToBean

import org.springframework.util.ReflectionUtils; //导入依赖的package包/类
/**
 * Copy the properties of the supplied {@link Annotation} to the supplied target bean.
 * Any properties defined in {@code excludedProperties} will not be copied.
 * <p>A specified value resolver may resolve placeholders in property values, for example.
 * @param ann the annotation to copy from
 * @param bean the bean instance to copy to
 * @param valueResolver a resolve to post-process String property values (may be {@code null})
 * @param excludedProperties the names of excluded properties, if any
 * @see org.springframework.beans.BeanWrapper
 */
public static void copyPropertiesToBean(Annotation ann, Object bean, StringValueResolver valueResolver, String... excludedProperties) {
	Set<String> excluded =  new HashSet<String>(Arrays.asList(excludedProperties));
	Method[] annotationProperties = ann.annotationType().getDeclaredMethods();
	BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(bean);
	for (Method annotationProperty : annotationProperties) {
		String propertyName = annotationProperty.getName();
		if ((!excluded.contains(propertyName)) && bw.isWritableProperty(propertyName)) {
			Object value = ReflectionUtils.invokeMethod(annotationProperty, ann);
			if (valueResolver != null && value instanceof String) {
				value = valueResolver.resolveStringValue((String) value);
			}
			bw.setPropertyValue(propertyName, value);
		}
	}
}
 
开发者ID:lamsfoundation,项目名称:lams,代码行数:26,代码来源:AnnotationBeanUtils.java

示例7: getSortedService

import org.springframework.util.ReflectionUtils; //导入依赖的package包/类
public static <T> List<T> getSortedService(Class<T> serviceType) {
  List<Entry<Integer, T>> serviceEntries = new ArrayList<>();
  ServiceLoader<T> serviceLoader = ServiceLoader.load(serviceType);
  serviceLoader.forEach(service -> {
    int serviceOrder = 0;
    Method getOrder = ReflectionUtils.findMethod(service.getClass(), "getOrder");
    if (getOrder != null) {
      serviceOrder = (int) ReflectionUtils.invokeMethod(getOrder, service);
    }

    Entry<Integer, T> entry = new SimpleEntry<>(serviceOrder, service);
    serviceEntries.add(entry);
  });

  return serviceEntries.stream()
      .sorted(Comparator.comparingInt(Entry::getKey))
      .map(Entry::getValue)
      .collect(Collectors.toList());
}
 
开发者ID:apache,项目名称:incubator-servicecomb-java-chassis,代码行数:20,代码来源:SPIServiceUtils.java

示例8: execute

import org.springframework.util.ReflectionUtils; //导入依赖的package包/类
@Override
public TypedValue execute(EvaluationContext context, Object target, Object... arguments) throws AccessException {
	try {
		if (arguments != null) {
			ReflectionHelper.convertArguments(context.getTypeConverter(), arguments, this.method, this.varargsPosition);
		}
		if (this.method.isVarArgs()) {
			arguments = ReflectionHelper.setupArgumentsForVarargsInvocation(this.method.getParameterTypes(), arguments);
		}
		ReflectionUtils.makeAccessible(this.method);
		Object value = this.method.invoke(target, arguments);
		return new TypedValue(value, new TypeDescriptor(new MethodParameter(this.method, -1)).narrow(value));
	}
	catch (Exception ex) {
		throw new AccessException("Problem invoking method: " + this.method, ex);
	}
}
 
开发者ID:lamsfoundation,项目名称:lams,代码行数:18,代码来源:ReflectiveMethodExecutor.java

示例9: toCommand

import org.springframework.util.ReflectionUtils; //导入依赖的package包/类
@Override
public Object toCommand(LockedExternalTaskDto task) {
    ExternalTask<?> externalTask = getExternalTask(task.getTopicName());

    Object command = JavaUtils.callWithoutCheckedException(() -> externalTask.getClazz().newInstance());

    externalTask.getFields().forEach((varName, field) -> {
        if (task.getVariables() != null) {
            task.getVariables().computeIfPresent(varName, (name, value) -> {
                JavaUtils.setFieldWithoutCheckedException(field, command, value.getValue());
                return value;
            });
        }

        Field taskField = ReflectionUtils.findField(task.getClass(), varName);
        if (taskField != null) {
            ReflectionUtils.makeAccessible(taskField);
            JavaUtils.setFieldWithoutCheckedException(field, command, () -> taskField.get(task));
        }
    });

    return command;
}
 
开发者ID:EsikAntony,项目名称:camunda-task-dispatcher,代码行数:24,代码来源:ExternalTaskManagerImpl.java

示例10: overridingIntervalAndCollectionNameThroughAnnotationShouldWork

import org.springframework.util.ReflectionUtils; //导入依赖的package包/类
@Test
public void overridingIntervalAndCollectionNameThroughAnnotationShouldWork() throws IllegalAccessException {

	this.context = new AnnotationConfigApplicationContext();
	this.context.register(OverrideMongoParametersConfig.class);
	this.context.refresh();

	ReactiveMongoOperationsSessionRepository repository = this.context.getBean(ReactiveMongoOperationsSessionRepository.class);

	Field inactiveField = ReflectionUtils.findField(ReactiveMongoOperationsSessionRepository.class, "maxInactiveIntervalInSeconds");
	ReflectionUtils.makeAccessible(inactiveField);
	Integer inactiveSeconds = (Integer) inactiveField.get(repository);

	Field collectionNameField = ReflectionUtils.findField(ReactiveMongoOperationsSessionRepository.class, "collectionName");
	ReflectionUtils.makeAccessible(collectionNameField);
	String collectionName = (String) collectionNameField.get(repository);

	assertThat(inactiveSeconds).isEqualTo(123);
	assertThat(collectionName).isEqualTo("test-case");
}
 
开发者ID:spring-projects,项目名称:spring-session-data-mongodb,代码行数:21,代码来源:ReactiveMongoWebSessionConfigurationTest.java

示例11: init

import org.springframework.util.ReflectionUtils; //导入依赖的package包/类
@Before
public void init() {
    listener = new JmsExternalCommandListener();

    JavaUtils.setFieldWithoutCheckedException(
            ReflectionUtils.findField(JmsExternalCommandListener.class, "taskService")
            , listener
            , taskService
    );
    JavaUtils.setFieldWithoutCheckedException(
            ReflectionUtils.findField(JmsExternalCommandListener.class, "taskManager")
            , listener
            , taskManager
    );
    JavaUtils.setFieldWithoutCheckedException(
            ReflectionUtils.findField(JmsExternalCommandListener.class, "taskMapper")
            , listener
            , taskMapper
    );
    JavaUtils.setFieldWithoutCheckedException(
            ReflectionUtils.findField(JmsExternalCommandListener.class, "jmsTemplate")
            , listener
            , jmsTemplate
    );
}
 
开发者ID:EsikAntony,项目名称:camunda-task-dispatcher,代码行数:26,代码来源:JmsExternalCommandListenerTest.java

示例12: convertRmiAccessException

import org.springframework.util.ReflectionUtils; //导入依赖的package包/类
/**
 * Convert the given RemoteException that happened during remote access
 * to Spring's RemoteAccessException if the method signature does not
 * support RemoteException. Else, return the original RemoteException.
 * @param method the invoked method
 * @param ex the RemoteException that happened
 * @param isConnectFailure whether the given exception should be considered
 * a connect failure
 * @param serviceName the name of the service (for debugging purposes)
 * @return the exception to be thrown to the caller
 */
public static Exception convertRmiAccessException(
		Method method, RemoteException ex, boolean isConnectFailure, String serviceName) {

	if (logger.isDebugEnabled()) {
		logger.debug("Remote service [" + serviceName + "] threw exception", ex);
	}
	if (ReflectionUtils.declaresException(method, ex.getClass())) {
		return ex;
	}
	else {
		if (isConnectFailure) {
			return new RemoteConnectFailureException("Could not connect to remote service [" + serviceName + "]", ex);
		}
		else {
			return new RemoteAccessException("Could not access remote service [" + serviceName + "]", ex);
		}
	}
}
 
开发者ID:lamsfoundation,项目名称:lams,代码行数:30,代码来源:RmiClientInterceptorUtils.java

示例13: addCookie

import org.springframework.util.ReflectionUtils; //导入依赖的package包/类
/**
 * Adds the cookie, taking into account {@link RememberMeCredential#REQUEST_PARAMETER_REMEMBER_ME}
 * in the request.
 *
 * @param request the request
 * @param response the response
 * @param cookieValue the cookie value
 */
public void addCookie(final HttpServletRequest request, final HttpServletResponse response, final String cookieValue) {
    final String theCookieValue = this.casCookieValueManager.buildCookieValue(cookieValue, request);

    if (!StringUtils.hasText(request.getParameter(RememberMeCredential.REQUEST_PARAMETER_REMEMBER_ME))) {
        super.addCookie(response, theCookieValue);
    } else {
        final Cookie cookie = createCookie(theCookieValue);
        cookie.setMaxAge(this.rememberMeMaxAge);
        if (isCookieSecure()) {
            cookie.setSecure(true);
        }
        if (isCookieHttpOnly()) {
            final Method setHttpOnlyMethod = ReflectionUtils.findMethod(Cookie.class, "setHttpOnly", boolean.class);
            if(setHttpOnlyMethod != null) {
                cookie.setHttpOnly(true);
            } else {
                logger.debug("Cookie cannot be marked as HttpOnly; container is not using servlet 3.0.");
            }
        }
        response.addCookie(cookie);
    }
}
 
开发者ID:hsj-xiaokang,项目名称:springboot-shiro-cas-mybatis,代码行数:31,代码来源:CookieRetrievingCookieGenerator.java

示例14: invokeMethod

import org.springframework.util.ReflectionUtils; //导入依赖的package包/类
/**
 * 调用方法,可以是一些私有方法
 * 
 * @param target
 * @param methodName
 * @param args
 * @return
 * @throws Exception
 */
public static Object invokeMethod(Object target, String methodName, Object... args) throws Exception {
    Method method = null;
    // 查找对应的方法
    if (args == null || args.length == 0) {
        method = ReflectionUtils.findMethod(target.getClass(), methodName);
    } else {
        Class[] argsClass = new Class[args.length];
        for (int i = 0; i < args.length; i++) {
            argsClass[i] = args[i].getClass();
        }
        method = ReflectionUtils.findMethod(target.getClass(), methodName, argsClass);
    }
    ReflectionUtils.makeAccessible(method);

    if (args == null || args.length == 0) {
        return ReflectionUtils.invokeMethod(method, target);
    } else {
        return ReflectionUtils.invokeMethod(method, target, args);
    }
}
 
开发者ID:luoyaogui,项目名称:otter-G,代码行数:30,代码来源:TestUtils.java

示例15: getGuild

import org.springframework.util.ReflectionUtils; //导入依赖的package包/类
@Override
public Guild getGuild(Event event) {
    if (event == null) {
        return null;
    }
    Class<? extends Event> clazz = event.getClass();
    Method method;
    if (!guildAccessors.containsKey(clazz)) {
        method = ReflectionUtils.findMethod(clazz, "getGuild");
        guildAccessors.put(clazz, method);
    } else {
        method = guildAccessors.get(clazz);
    }
    if (method != null) {
        Object result = ReflectionUtils.invokeMethod(method, event);
        if (result instanceof Guild) {
            return (Guild) result;
        }
    }
    return null;
}
 
开发者ID:GoldRenard,项目名称:JuniperBotJ,代码行数:22,代码来源:SourceResolverServiceImpl.java


注:本文中的org.springframework.util.ReflectionUtils类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。