Example usage for java.lang.reflect Field set

List of usage examples for java.lang.reflect Field set

Introduction

In this page you can find the example usage for java.lang.reflect Field set.

Prototype

@CallerSensitive
@ForceInline 
public void set(Object obj, Object value) throws IllegalArgumentException, IllegalAccessException 

Source Link

Document

Sets the field represented by this Field object on the specified object argument to the specified new value.

Usage

From source file:jenkins.security.apitoken.ApiTokenStatsTest.java

private ApiTokenStats.SingleTokenStats createSingleTokenStatsByReflection(String uuid, String dateString,
        Integer counter) throws Exception {
    Class<ApiTokenStats.SingleTokenStats> clazz = ApiTokenStats.SingleTokenStats.class;
    Constructor<ApiTokenStats.SingleTokenStats> constructor = clazz.getDeclaredConstructor(String.class);
    constructor.setAccessible(true);/*www  . j  a  v  a  2 s  . c om*/

    ApiTokenStats.SingleTokenStats result = constructor.newInstance(uuid);

    {
        Field field = clazz.getDeclaredField("useCounter");
        field.setAccessible(true);
        field.set(result, counter);
    }
    if (dateString != null) {
        Field field = clazz.getDeclaredField("lastUseDate");
        field.setAccessible(true);
        field.set(result, new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").parse(dateString));
    }

    return result;
}

From source file:org.agorava.linkedin.jackson.LinkedInNetworkUpdateListDeserializer.java

@Override
public LinkedInNetworkUpdate deserialize(JsonParser jp, DeserializationContext ctxt)
        throws IOException, JsonProcessingException {
    ObjectMapper mapper = BeanResolver.getInstance().resolve(ObjectMapper.class);
    jp.setCodec(mapper);/* ww w. j  av  a  2s  .c o  m*/

    JsonNode dataNode = jp.readValueAs(JsonNode.class);
    if (dataNode != null) {
        LinkedInNetworkUpdate linkedInNetworkUpdate = (LinkedInNetworkUpdate) mapper
                .reader(new TypeReference<LinkedInNetworkUpdate>() {
                }).readValue(dataNode);

        UpdateContent updatedContent = null;
        UpdateType type = linkedInNetworkUpdate.getUpdateType();
        JsonNode updatedNode = dataNode.get("updateContent");
        JsonNode person = updatedNode.get("person");
        if (type == UpdateType.MSFC) {
            // Totally different.  Looks like a bad API to be honest.
            person = updatedNode.get("companyPersonUpdate").get("person");
        }

        switch (type) {
        case CONN:
            updatedContent = mapper.reader(new TypeReference<UpdateContentConnection>() {
            }).readValue(person);
            break;
        case STAT:
            updatedContent = mapper.reader(new TypeReference<UpdateContentStatus>() {
            }).readValue(person);
            break;
        case JGRP:
            updatedContent = mapper.reader(new TypeReference<UpdateContentGroup>() {
            }).readValue(person);
            break;
        case PREC:
        case SVPR:
            updatedContent = mapper.reader(new TypeReference<UpdateContentRecommendation>() {
            }).readValue(person);
            break;
        case APPM:
            updatedContent = mapper.reader(new TypeReference<UpdateContentPersonActivity>() {
            }).readValue(person);
            break;
        case MSFC:
            updatedContent = mapper.reader(new TypeReference<UpdateContentFollow>() {
            }).readValue(person);
            break;
        case VIRL:
            updatedContent = mapper.reader(new TypeReference<UpdateContentViral>() {
            }).readValue(person);
            break;
        case SHAR:
            updatedContent = mapper.reader(new TypeReference<UpdateContentShare>() {
            }).readValue(person);
            break;
        case CMPY:
            updatedContent = mapper.reader(new TypeReference<UpdateContentCompany>() {
            }).readValue(updatedNode);
            break;
        default:
            try {
                updatedContent = mapper.reader(new TypeReference<UpdateContent>() {
                }).readValue(person);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }

        // Need to use reflection to set private updateContent field
        try {
            Field f = LinkedInNetworkUpdate.class.getDeclaredField("updateContent");
            f.setAccessible(true);
            f.set(linkedInNetworkUpdate, updatedContent);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        if (type == UpdateType.MSFC) {
            // Set the action via reflection as it's private
            String action = updatedNode.get("companyPersonUpdate").get("action").get("code").asText();
            try {
                Field f = UpdateContentFollow.class.getDeclaredField("action");
                f.setAccessible(true);
                f.set(updatedContent, action);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }

            // Set following via reflection as it's private
            Company company = mapper.reader(new TypeReference<Company>() {
            }).readValue(updatedNode.get("company"));
            try {
                Field f = UpdateContentFollow.class.getDeclaredField("following");
                f.setAccessible(true);
                f.set(updatedContent, company);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        } else if (type == UpdateType.VIRL) {
            JsonNode originalUpdate = updatedNode.path("updateAction").path("originalUpdate");
            UpdateAction updateAction = mapper.reader(new TypeReference<UpdateAction>() {
            }).readValue(originalUpdate);
            String code = updatedNode.path("updateAction").path("action").path("code").textValue();

            // Set private immutable field action on updateAction
            try {
                Field f = UpdateAction.class.getDeclaredField("action");
                f.setAccessible(true);
                f.set(updateAction, code);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }

            // Set private immutable field  updateAction on updatedContent
            try {
                Field f = UpdateContentViral.class.getDeclaredField("updateAction");
                f.setAccessible(true);
                f.set(updatedContent, updateAction);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }

        return linkedInNetworkUpdate;
    }

    return null;
}

From source file:com.yahoo.pulsar.broker.namespace.NamespaceServiceTest.java

@Test
public void testIsServiceUnitDisabled() throws Exception {

    OwnershipCache MockOwnershipCache = spy(pulsar.getNamespaceService().getOwnershipCache());

    ManagedLedger ledger = mock(ManagedLedger.class);
    when(ledger.getCursors()).thenReturn(Lists.newArrayList());

    doNothing().when(MockOwnershipCache).disableOwnership(any(NamespaceBundle.class));
    Field ownership = NamespaceService.class.getDeclaredField("ownershipCache");
    ownership.setAccessible(true);//from ww  w  . java  2 s  . co m
    ownership.set(pulsar.getNamespaceService(), MockOwnershipCache);

    NamespaceService namespaceService = pulsar.getNamespaceService();
    NamespaceName nsname = new NamespaceName("pulsar/global/ns1");
    DestinationName dn = DestinationName.get("persistent://pulsar/global/ns1/topic-1");
    NamespaceBundles bundles = namespaceService.getNamespaceBundleFactory().getBundles(nsname);
    NamespaceBundle originalBundle = bundles.findBundle(dn);

    assertFalse(namespaceService.isNamespaceBundleDisabled(originalBundle));

}

From source file:com.yahoo.pulsar.broker.namespace.NamespaceServiceTest.java

@Test
public void testremoveOwnershipNamespaceBundle() throws Exception {

    OwnershipCache ownershipCache = spy(pulsar.getNamespaceService().getOwnershipCache());

    ManagedLedger ledger = mock(ManagedLedger.class);
    when(ledger.getCursors()).thenReturn(Lists.newArrayList());

    doNothing().when(ownershipCache).disableOwnership(any(NamespaceBundle.class));
    Field ownership = NamespaceService.class.getDeclaredField("ownershipCache");
    ownership.setAccessible(true);/*  www  .  j  av a2  s .co  m*/
    ownership.set(pulsar.getNamespaceService(), ownershipCache);

    NamespaceService namespaceService = pulsar.getNamespaceService();
    NamespaceName nsname = new NamespaceName("prop/use/ns1");
    NamespaceBundles bundles = namespaceService.getNamespaceBundleFactory().getBundles(nsname);

    NamespaceBundle bundle = bundles.getBundles().get(0);
    assertNotNull(ownershipCache.tryAcquiringOwnership(bundle));
    assertNotNull(ownershipCache.getOwnedBundle(bundle));
    ownershipCache.removeOwnership(bundles).get();
    assertNull(ownershipCache.getOwnedBundle(bundle));
}

From source file:com.jfinal.plugin.spring.IocInterceptor.java

private void injectField(Controller controller, Field field) {
    Object bean = null;/*  w  ww .j a v  a 2 s .  com*/
    if (field.isAnnotationPresent(Inject.BY_NAME.class))
        bean = ctx.getBean(field.getName());
    else if (field.isAnnotationPresent(Inject.IGNORE.class))
        return;
    else
        bean = ctx.getBean(field.getType());

    try {
        field.setAccessible(true);
        field.set(controller, bean);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:cn.org.once.cstack.cli.processor.LoggerPostProcessor.java

public Object postProcessBeforeInitialization(final Object bean, String beanName) throws BeansException {
    ReflectionUtils.doWithFields(bean.getClass(), new ReflectionUtils.FieldCallback() {

        public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {

            if (field.getAnnotation(InjectLogger.class) != null && field.getType().equals(Logger.class)) {
                ReflectionUtils.makeAccessible(field);
                Logger logger = Logger.getLogger(bean.getClass().getName());

                field.set(bean, logger);

                StreamHandler fileHandler;
                try {

                    FileOutputStream fileOutputStream = new FileOutputStream(new File("errors.log"), true);
                    fileHandler = new StreamHandler(fileOutputStream, new SimpleFormatter());
                    fileHandler.setLevel(Level.SEVERE);
                    logger.addHandler(fileHandler);

                } catch (SecurityException | IOException e) {
                    throw new IllegalArgumentException(e);
                }//from  w w  w . j a  va  2  s.  c  o  m

            }
        }
    });

    return bean;
}

From source file:com.ml.ws.service.CommonService.java

private void transResult(Map<String, Object> map, Object obj) {

    for (String key : map.keySet()) {
        key.toLowerCase();/*w  w  w. j  a  va  2 s.  co m*/
    }

    for (Field field : obj.getClass().getDeclaredFields()) {
        final String name = field.getName();
        if (name.equalsIgnoreCase("serialVersionUID")) {
            continue;
        }
        field.setAccessible(true);
        try {
            field.set(obj, map.get(name));
        } catch (IllegalArgumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

From source file:com.autonomy.aci.client.services.impl.AbstractStAXProcessorTest.java

@Test
public void testNullXMLStreamReader() throws NoSuchFieldException, XMLStreamException, IllegalAccessException {
    final AbstractStAXProcessor<?> abstractStAXProcessor = spy(AbstractStAXProcessor.class);

    final Field field = ReflectionTestUtils.getAccessibleField(AbstractStAXProcessor.class, "xmlInputFactory");
    field.set(abstractStAXProcessor,
            when(mock(XMLInputFactory.class).createXMLStreamReader(any(AciResponseInputStream.class)))
                    .thenReturn(null).getMock());

    abstractStAXProcessor.process(when(mock(AciResponseInputStream.class).getContentType())
            .thenReturn("text/xml").<AciResponseInputStream>getMock());
}

From source file:com.agileapes.couteau.context.spring.event.impl.AbstractMappedEventsTranslationScheme.java

@Override
public ApplicationEvent translate(Event originalEvent) throws EventTranslationException {
    final Class<? extends ApplicationEvent> eventClass;
    try {//from www .java 2s  .c  o  m
        eventClass = getTargetEvent(originalEvent.getClass());
    } catch (ClassNotFoundException e) {
        throw new EventTranslationException("Failed to locate target class for event", e);
    }
    final ApplicationEvent applicationEvent;
    try {
        applicationEvent = eventClass.getConstructor(Object.class).newInstance(originalEvent.getSource());
    } catch (Exception e) {
        throw new EventTranslationException(
                "Failed to instantiate event from " + eventClass.getCanonicalName());
    }
    for (Method method : originalEvent.getClass().getMethods()) {
        if (!GenericTranslationScheme.isGetter(method)) {
            continue;
        }
        final String fieldName = StringUtils
                .uncapitalize(method.getName().substring(method.getName().startsWith("get") ? 3 : 2));
        final Field field = ReflectionUtils.findField(eventClass, fieldName);
        if (field == null || !field.getType().isAssignableFrom(method.getReturnType())) {
            continue;
        }
        field.setAccessible(true);
        try {
            field.set(applicationEvent, method.invoke(originalEvent));
        } catch (Exception e) {
            throw new EventTranslationException("Failed to set property: " + fieldName, e);
        }
    }
    return applicationEvent;
}