Java 类org.springframework.util.ReflectionUtils 实例源码

项目:service-hive    文件:RateLimitZuulFilter.java   
@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;
}
项目:cloud-native-reference    文件:ThrottlingPreFilter.java   
@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;
}
项目:spring-cloud-sockets    文件:DispatcherHandler.java   
@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();
}
项目:JuniperBotJ    文件:SourceResolverServiceImpl.java   
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;
}
项目:lams    文件:JBossModulesAdapter.java   
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);
    }
}
项目:lams    文件:AnnotationBeanUtils.java   
/**
 * 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);
        }
    }
}
项目:incubator-servicecomb-java-chassis    文件:SPIServiceUtils.java   
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());
}
项目:lams    文件:ReflectiveMethodExecutor.java   
@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);
    }
}
项目:camunda-task-dispatcher    文件:ExternalTaskManagerImpl.java   
@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;
}
项目:spring-session-data-mongodb    文件:ReactiveMongoWebSessionConfigurationTest.java   
@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");
}
项目:picocli-spring-boot-starter    文件:PicocliAutoConfiguration.java   
private Object getMainCommand(Collection<Object> candidates) {
    Object mainCommand = null;
    for (Object candidate : candidates) {
        Class<?> clazz = AopUtils.getTargetClass(candidate);
        Method method = ReflectionUtils.findMethod(Command.class, "name");
        if (clazz.isAnnotationPresent(Command.class)
                && method != null
                && clazz.getAnnotation(Command.class).name().equals(method.getDefaultValue())) {
            mainCommand = candidate;
            break;
        }
    }
    if (mainCommand == null) {
        mainCommand = new PicocliCommand() {};
    }
    return mainCommand;
}
项目:camunda-task-dispatcher    文件:JmsExternalCommandListenerTest.java   
@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
    );
}
项目:lams    文件:RmiClientInterceptorUtils.java   
/**
 * 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);
        }
    }
}
项目:springboot-shiro-cas-mybatis    文件:CookieRetrievingCookieGenerator.java   
/**
 * 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);
    }
}
项目:otter-G    文件:TestUtils.java   
/**
 * 调用方法,可以是一些私有方法
 * 
 * @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);
    }
}
项目:JuniperBotJ    文件:SourceResolverServiceImpl.java   
@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;
}
项目:os    文件:CheckingEntityListener.java   
@PostLoad
public void checking(Object target) {
    AnnotationCheckingMetadata metadata = AnnotationCheckingMetadata.getMetadata(target.getClass());
    if (metadata.isCheckable()) {
        StringBuilder sb = new StringBuilder();
        for (Field field : metadata.getCheckedFields()) {
            ReflectionUtils.makeAccessible(field);
            Object value = ReflectionUtils.getField(field, target);
            if (value instanceof Date) {
                throw new RuntimeException("不支持时间类型字段解密!");
            }
            sb.append(value).append(" - ");
        }
        sb.append(MD5_KEY);
        LOGGER.debug("验证数据:" + sb);
        String hex = MD5Utils.encode(sb.toString());
        Field checksumField = metadata.getCheckableField();
        ReflectionUtils.makeAccessible(checksumField);
        String checksum = (String) ReflectionUtils.getField(checksumField, target);
        if (!checksum.equals(hex)) {
            //throw new RuntimeException("数据验证失败!");
        }
    }
}
项目:lams    文件:ConstructorResolver.java   
/**
 * Retrieve all candidate methods for the given class, considering
 * the {@link RootBeanDefinition#isNonPublicAccessAllowed()} flag.
 * Called as the starting point for factory method determination.
 */
private Method[] getCandidateMethods(final Class<?> factoryClass, final RootBeanDefinition mbd) {
    if (System.getSecurityManager() != null) {
        return AccessController.doPrivileged(new PrivilegedAction<Method[]>() {
            @Override
            public Method[] run() {
                return (mbd.isNonPublicAccessAllowed() ?
                        ReflectionUtils.getAllDeclaredMethods(factoryClass) : factoryClass.getMethods());
            }
        });
    }
    else {
        return (mbd.isNonPublicAccessAllowed() ?
                ReflectionUtils.getAllDeclaredMethods(factoryClass) : factoryClass.getMethods());
    }
}
项目:spring-data-documentdb    文件:DocumentDbEntityInformation.java   
public DocumentDbEntityInformation(Class<T> domainClass) {
    super(domainClass);

    this.id = getIdField(domainClass);
    if (this.id != null) {
        ReflectionUtils.makeAccessible(this.id);
    }

    this.collectionName = getCollectionName(domainClass);
    this.partitionKeyField = getPartitionKeyField(domainClass);
    if (this.partitionKeyField != null) {
        ReflectionUtils.makeAccessible(this.partitionKeyField);
    }

    this.requestUnit = getRequestUnit(domainClass);
}
项目:otter-G    文件:TestUtils.java   
/**
 * 调用方法,可以是一些私有方法
 * 
 * @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);
    }
}
项目:bootstrap    文件:CsvForJpa.java   
/**
 * Return JPA managed properties.
 * 
 * @param <T>
 *            Bean type.
 * @param beanType
 *            the bean type.
 * @return the headers built from given type.
 */
public <T> String[] getJpaHeaders(final Class<T> beanType) {
    // Build descriptor list respecting the declaration order
    final OrderedFieldCallback fieldCallBack = new OrderedFieldCallback();
    ReflectionUtils.doWithFields(beanType, fieldCallBack);
    final List<String> orderedDescriptors = fieldCallBack.descriptorsOrdered;

    // Now filter the properties
    final List<String> descriptorsFiltered = new ArrayList<>();
    final ManagedType<T> managedType = transactionManager.getEntityManagerFactory().getMetamodel().managedType(beanType);
    for (final String propertyDescriptor : orderedDescriptors) {
        for (final Attribute<?, ?> attribute : managedType.getAttributes()) {
            // Match only basic attributes
            if (attribute instanceof SingularAttribute<?, ?> && propertyDescriptor.equals(attribute.getName())) {
                descriptorsFiltered.add(attribute.getName());
                break;
            }
        }
    }

    // Initialize the CSV reader
    return descriptorsFiltered.toArray(new String[descriptorsFiltered.size()]);
}
项目:tasfe-framework    文件:EnumFieldReflectUtil.java   
/**
 * 设置枚举类型的字段值
 *
 * @param target  the target object from which to get the field
 * @param field   the field to set
 * @param ordinal enum.ordinal
 * @throws Exception IllegalArgumentException, IllegalAccess
 */
@SuppressWarnings("rawtypes")
public static void setFieldEnumValueByOrdinal(Object target, Field field, int ordinal) throws Exception {
    if (field.getType().isEnum()) {
        if (!field.isAccessible()) {
            ReflectionUtils.makeAccessible(field);
        }
        Enum[] enumObjs = (Enum[]) (field.getType()).getEnumConstants();
        for (Enum enumObj : enumObjs) {
            if (enumObj.ordinal() == ordinal) {
                field.set(target, enumObj);
            }
        }
    } else {
        throw new ReflectionException(target.getClass().getName() + "." + field.getName()
                + ":field type is not Enum, can not convertToEnum");
    }
}
项目:Cloud-Foundry-For-Developers    文件:HomeController.java   
private String toString(DataSource dataSource) {
    if (dataSource == null) {
        return "<none>";
    } else {
        try {
            Field urlField = ReflectionUtils.findField(dataSource.getClass(), "url");
            ReflectionUtils.makeAccessible(urlField);
            return stripCredentials((String) urlField.get(dataSource));
        } catch (Exception fe) {
            try {
                Method urlMethod = ReflectionUtils.findMethod(dataSource.getClass(), "getUrl");
                ReflectionUtils.makeAccessible(urlMethod);
                return stripCredentials((String) urlMethod.invoke(dataSource, (Object[])null));
            } catch (Exception me){
                return "<unknown> " + dataSource.getClass();
            }
        }
    }
}
项目:Cloud-Foundry-For-Developers    文件:HomeController.java   
private String toString(DataSource dataSource) {
    if (dataSource == null) {
        return "<none>";
    } else {
        try {
            Field urlField = ReflectionUtils.findField(dataSource.getClass(), "url");
            ReflectionUtils.makeAccessible(urlField);
            return stripCredentials((String) urlField.get(dataSource));
        } catch (Exception fe) {
            try {
                Method urlMethod = ReflectionUtils.findMethod(dataSource.getClass(), "getUrl");
                ReflectionUtils.makeAccessible(urlMethod);
                return stripCredentials((String) urlMethod.invoke(dataSource, (Object[])null));
            } catch (Exception me){
                return "<unknown> " + dataSource.getClass();
            }
        }
    }
}
项目:gemini.blueprint    文件:AbstractOsgiTests.java   
/**
 * Determines through reflection the methods used for invoking the TestRunnerService.
 *
 * @throws Exception
 */
private void initializeServiceRunnerInvocationMethods() throws Exception {
    // get JUnit test service reference
    // this is a loose reference - update it if the JUnitTestActivator class is changed.

    BundleContext ctx = getRuntimeBundleContext();

    ServiceReference reference = ctx.getServiceReference(ACTIVATOR_REFERENCE);
    Assert.notNull(reference, "no OSGi service reference found at " + ACTIVATOR_REFERENCE);

    service = ctx.getService(reference);
    Assert.notNull(service, "no service found for reference: " + reference);

    serviceTrigger = service.getClass().getDeclaredMethod("executeTest", new Class[0]);
    ReflectionUtils.makeAccessible(serviceTrigger);
    Assert.notNull(serviceTrigger, "no executeTest() method found on: " + service.getClass());
}
项目:gemini.blueprint    文件:ServiceReferenceInjectionBeanPostProcessor.java   
private void injectServicesViaAnnotatedSetterMethods(final Object bean, final String beanName) {
    ReflectionUtils.doWithMethods(bean.getClass(), new ReflectionUtils.MethodCallback() {

        public void doWith(Method method) {
            ServiceReference s = AnnotationUtils.getAnnotation(method, ServiceReference.class);
            if (s != null && method.getParameterTypes().length == 1) {
                try {
                    if (logger.isDebugEnabled())
                        logger.debug("Processing annotation [" + s + "] for [" + bean.getClass().getName() + "."
                                + method.getName() + "()] on bean [" + beanName + "]");
                    method.invoke(bean, getServiceImporter(s, method, beanName).getObject());
                }
                catch (Exception e) {
                    throw new IllegalArgumentException("Error processing service annotation", e);
                }
            }
        }
    });
}
项目:spring-cloud-skipper    文件:StateMachineTests.java   
private static void setId(Class<?> clazz, Object instance, String fieldName, Object value) {
    try {
        Field field = ReflectionUtils.findField(clazz, fieldName);
        field.setAccessible(true);
        int modifiers = field.getModifiers();
        Field modifierField = field.getClass().getDeclaredField("modifiers");
        modifiers = modifiers & ~Modifier.FINAL;
        modifierField.setAccessible(true);
        modifierField.setInt(field, modifiers);
        ReflectionUtils.setField(field, instance, value);
    } catch (ReflectiveOperationException e) {
        throw new IllegalArgumentException(e);
    }
}
项目:FastBootWeixin    文件:WxMenuAnnotationProcessor.java   
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
    Class<?> targetClass = AopUtils.getTargetClass(bean);
    ReflectionUtils.doWithMethods(targetClass, method -> {
        WxButton wxButton = AnnotationUtils.getAnnotation(method, WxButton.class);
        if (wxButton != null) {
            wxMenuManager.add(wxButton);
        }
    });
    return bean;
}
项目:incubator-servicecomb-java-chassis    文件:Utils.java   
public static Object getFieldValue(Object instance, String fieldName) {
  try {
    return ReflectionUtils.findField(instance.getClass(), fieldName).get(instance);
  } catch (Exception e) {
    throw new Error(e);
  }
}
项目:incubator-servicecomb-java-chassis    文件:MockUtil.java   
public void mockReflectionUtils() {

    new MockUp<ReflectionUtils>() {
      @Mock
      Object getField(Field field, Object target) {
        Response response = Response.ok(200);
        return new CseClientHttpResponse(response);
      }
    };
  }
项目:lams    文件:AdaptableJobFactory.java   
/**
 * Create an instance of the specified job class.
 * <p>Can be overridden to post-process the job instance.
 * @param bundle the TriggerFiredBundle from which the JobDetail
 * and other info relating to the trigger firing can be obtained
 * @return the job instance
 * @throws Exception if job instantiation failed
 */
protected Object createJobInstance(TriggerFiredBundle bundle) throws Exception {
    // Reflectively adapting to differences between Quartz 1.x and Quartz 2.0...
    Method getJobDetail = bundle.getClass().getMethod("getJobDetail");
    Object jobDetail = ReflectionUtils.invokeMethod(getJobDetail, bundle);
    Method getJobClass = jobDetail.getClass().getMethod("getJobClass");
    Class<?> jobClass = (Class<?>) ReflectionUtils.invokeMethod(getJobClass, jobDetail);
    return jobClass.newInstance();
}
项目:lams    文件:JndiRmiClientInterceptor.java   
/**
 * Convert the given CORBA SystemException that happened during remote access
 * to Spring's RemoteAccessException if the method signature does not declare
 * RemoteException. Else, return the SystemException wrapped in a RemoteException.
 * @param method the invoked method
 * @param ex the RemoteException that happened
 * @return the exception to be thrown to the caller
 */
private Exception convertCorbaAccessException(SystemException ex, Method method) {
    if (ReflectionUtils.declaresException(method, RemoteException.class)) {
        // A traditional RMI service: wrap CORBA exceptions in standard RemoteExceptions.
        return new RemoteException("Failed to access CORBA service [" + getJndiName() + "]", ex);
    }
    else {
        if (isConnectFailure(ex)) {
            return new RemoteConnectFailureException("Could not connect to CORBA service [" + getJndiName() + "]", ex);
        }
        else {
            return new RemoteAccessException("Could not access CORBA service [" + getJndiName() + "]", ex);
        }
    }
}
项目:lams    文件:JBossNativeJdbcExtractor.java   
/**
 * Retrieve the Connection via JBoss' {@code getUnderlyingResultSet} method.
 */
@Override
public ResultSet getNativeResultSet(ResultSet rs) throws SQLException {
    if (this.wrappedResultSetClass.isAssignableFrom(rs.getClass())) {
        return (ResultSet) ReflectionUtils.invokeJdbcMethod(this.getUnderlyingResultSetMethod, rs);
    }
    return rs;
}
项目:camunda-task-dispatcher    文件:ExternalTaskManagerImplTest.java   
@Before
public void init() {
    manager = new ExternalTaskManagerImpl();

    JavaUtils.setFieldWithoutCheckedException(
            ReflectionUtils.findField(ExternalTaskManagerImpl.class, "packages")
            , manager
            , Arrays.asList(Command.class.getPackage().getName())
    );
}
项目:camunda-task-dispatcher    文件:ExternalTaskManagerImplTest.java   
@Test
public void testToCommand() {
    manager.init();

    LockedExternalTaskDto task = EnhancedRandom.random(LockedExternalTaskDto.class);
    JavaUtils.setFieldWithoutCheckedException(
            ReflectionUtils.findField(LockedExternalTaskDto.class, "topicName")
            , task
            , Command.TASK_NAME
    );
    String stringVar = "value";
    String otherVar = "other value";

    task.getVariables().put("stringVar", VariableValueDto.fromTypedValue(new PrimitiveTypeValueImpl.StringValueImpl(stringVar)));
    task.getVariables().put("otherVar", VariableValueDto.fromTypedValue(new PrimitiveTypeValueImpl.StringValueImpl(otherVar)));

    Object object = manager.toCommand(task);
    Assert.assertNotNull(object);
    Assert.assertTrue(object instanceof Command);

    Command command = (Command) object;
    Assert.assertEquals(stringVar, command.getStringVar());
    Assert.assertEquals(otherVar, command.getAnotherStringVar());

    ReflectionUtils.doWithFields(LockedExternalTaskDto.class, field -> {
        if (field.getName().equals("variables")) {
            return;
        }

        Field commandField = ReflectionUtils.findField(Command.class, field.getName());
        Assert.assertNotNull("No field with name: " + field.getName(), commandField);
        Assert.assertEquals(
                JavaUtils.getFieldWithoutCheckedException(field, task)
                , JavaUtils.getFieldWithoutCheckedException(commandField, command)
        );
    });
}
项目:camunda-task-dispatcher    文件:JsonTaskMapperTest.java   
@Before
public void init() throws IOException {
    Mockito.when(objectMapper.writeValueAsString(Mockito.any())).thenReturn(JSON);
    Mockito.when(objectMapper.readValue(Mockito.anyString(), Mockito.<Class<SimpleCommand>>any())).thenReturn(COMMAND);

    mapper = new JsonTaskMapper();

    JavaUtils.setFieldWithoutCheckedException(
            ReflectionUtils.findField(JsonTaskMapper.class, "objectMapper")
            , mapper
            , objectMapper
    );
}
项目:gemini.blueprint    文件:LocalBundleContextAdviceTest.java   
protected void setUp() throws Exception {
    Method m = ReflectionUtils.findMethod(Object.class, "hashCode");
    context = new MockBundleContext();
    interceptor = new LocalBundleContextAdvice(context);

    invocation = new MockMethodInvocation(m) {
        public Object proceed() throws Throwable {
            assertSame("bundle context not set", context, LocalBundleContext.getInvokerBundleContext());
            return null;
        }
    };

}
项目:lams    文件:WebSphereDataSourceAdapter.java   
/**
 * Builds a WebSphere JDBCConnectionSpec object for the current settings
 * and calls {@code WSDataSource.getConnection(JDBCConnectionSpec)}.
 * @see #createConnectionSpec
 * @see com.ibm.websphere.rsadapter.WSDataSource#getConnection(com.ibm.websphere.rsadapter.JDBCConnectionSpec)
 */
@Override
protected Connection doGetConnection(String username, String password) throws SQLException {
    // Create JDBCConnectionSpec using current isolation level value and read-only flag.
    Object connSpec = createConnectionSpec(
            getCurrentIsolationLevel(), getCurrentReadOnlyFlag(), username, password);
    if (logger.isDebugEnabled()) {
        logger.debug("Obtaining JDBC Connection from WebSphere DataSource [" +
                getTargetDataSource() + "], using ConnectionSpec [" + connSpec + "]");
    }
    // Create Connection through invoking WSDataSource.getConnection(JDBCConnectionSpec)
    return (Connection) ReflectionUtils.invokeJdbcMethod(
            this.wsDataSourceGetConnectionMethod, getTargetDataSource(), connSpec);
}
项目:springboot-shiro-cas-mybatis    文件:CookieRetrievingCookieGenerator.java   
/**
 * Instantiates a new Cookie retrieving cookie generator.
 * @param casCookieValueManager the cookie manager
 */
public CookieRetrievingCookieGenerator(final CookieValueManager casCookieValueManager) {
    super();
    final Method setHttpOnlyMethod = ReflectionUtils.findMethod(Cookie.class, "setHttpOnly", boolean.class);
    if(setHttpOnlyMethod != null) {
        super.setCookieHttpOnly(true);
    } else {
        logger.debug("Cookie cannot be marked as HttpOnly; container is not using servlet 3.0.");
    }
    this.casCookieValueManager = casCookieValueManager;
}
项目:lams    文件:MBeanClientInterceptor.java   
private Object convertDataArrayToTargetArray(Object[] array, Class<?> targetClass) throws NoSuchMethodException {
    Class<?> targetType = targetClass.getComponentType();
    Method fromMethod = targetType.getMethod("from", array.getClass().getComponentType());
    Object resultArray = Array.newInstance(targetType, array.length);
    for (int i = 0; i < array.length; i++) {
        Array.set(resultArray, i, ReflectionUtils.invokeMethod(fromMethod, null, array[i]));
    }
    return resultArray;
}