Java 类org.apache.commons.lang.reflect.FieldUtils 实例源码

项目:export-distro    文件:IotCoreMQTTOutboundServiceActivatorTest.java   
@Before
public void setup() {
    activator = new IotCoreMQTTOutboundServiceActivator();
    string = ExportStringData.newTestInstance();
    string.setEventString(TEST_STRING);
    string.setEventId(TEST_ID);

    Addressable addressable = new Addressable(TEST_STRING, Protocol.OTHER, TEST_ADDRESS, TEST_PORT, TEST_PUBLISHER,
              TEST_USER, TEST_PASSWORD, TEST_TOPIC);
    ExportRegistration er = new ExportRegistration();
    er.setAddressable(addressable);
    string.setRegistration(er, TEST_ID);

    message = MessageBuilder.withPayload(string).build();
    try {
        FieldUtils.writeField(activator, "privateKeyFile", "rsa_private_pkcs8", true);
        FieldUtils.writeField(activator, "algorithm", "RS256", true);
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    }
}
项目:Mycat-Demo    文件:ReflectHelper.java   
public static Field getTargetField(Class<?> targetClass, String fieldName) {  
    Field field = null;  

    try {  
        if (targetClass == null) {  
            return field;  
        }  

        if (Object.class.equals(targetClass)) {  
            return field;  
        }  

        field = FieldUtils.getDeclaredField(targetClass, fieldName, true);  
        if (field == null) {  
            field = getTargetField(targetClass.getSuperclass(), fieldName);  
        }  
    } catch (Exception e) {  
    }  

    return field;  
}
项目:leopard    文件:BaseInfoBuilder.java   
protected Object toBaseInfoValue(String fieldName, String value) {
    Field field = FieldUtils.getField(BaseInfo.class, fieldName, true);
    // System.out.println("fieldName:" + fieldName + " field:" + field);
    Class<?> type = field.getType();
    if (ClassTypeUtil.isInteger(type)) {
        return Integer.parseInt(value);
    }
    else if (ClassTypeUtil.isLong(type)) {
        return Long.parseLong(value);
    }
    else if (ClassTypeUtil.isFloat(type)) {
        return Float.parseFloat(value);
    }
    else if (ClassTypeUtil.isDouble(type)) {
        return Double.parseDouble(value);
    }
    else if (type.equals(String.class)) {
        return value;
    }
    else {
        throw new IllegalArgumentException("未知类型[" + type.getName() + "].");
    }
}
项目:org.ops4j.ramler    文件:EnumsTest.java   
@SuppressWarnings("unchecked")
@Test
public void shouldFindEnumValues() throws IllegalAccessException {
    klass = modelPackage._getClass("Colour");
    assertThat(klass.getClassType()).isEqualTo(ClassType.ENUM);
    Map<String,JEnumConstant> enums = (Map<String, JEnumConstant>) FieldUtils.readField(klass, "enumConstantsByName", true);
    assertThat(enums.keySet()).contains("LIGHT_BLUE", "RED");

    JEnumConstant lightBlue = enums.get("LIGHT_BLUE");
    assertThat(lightBlue.javadoc().get(0)).isEqualTo("Colour of the sky");

    List<JExpression> args = (List<JExpression>) FieldUtils.readField(lightBlue, "args", true);
    assertThat(args).hasSize(1);

    assertThat(args.get(0)).isInstanceOf(JStringLiteral.class);

    String literal = (String) FieldUtils.readField(args.get(0), "str", true);
    assertThat(literal).isEqualTo("lightBlue");
}
项目:Camel    文件:SpringBatchEndpointTest.java   
@Test
public void shouldInjectJobLauncherByReferenceName() throws Exception {
    // Given
    context().addRoutes(new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            from("direct:launcherRefTest").to("spring-batch:mockJob?jobLauncher=#alternativeJobLauncher");
        }
    });

    // When
    template.sendBody("direct:launcherRefTest", "Start the job, please.");

    // Then
    SpringBatchEndpoint batchEndpoint = context().getEndpoint("spring-batch:mockJob?jobLauncher=#alternativeJobLauncher", SpringBatchEndpoint.class);
    JobLauncher batchEndpointJobLauncher = (JobLauncher) FieldUtils.readField(batchEndpoint, "jobLauncher", true);
    assertSame(alternativeJobLauncher, batchEndpointJobLauncher);
}
项目:Camel    文件:SpringBatchEndpointTest.java   
@Test
public void shouldResolveAnyJobLauncher() throws Exception {
    // Given
    SimpleRegistry registry = new SimpleRegistry();
    registry.put("mockJob", job);
    registry.put("someRandomName", jobLauncher);
    CamelContext camelContext = new DefaultCamelContext(registry);
    camelContext.addRoutes(new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            from("direct:start").to("spring-batch:mockJob");
        }
    });

    // When
    camelContext.start();

    // Then
    SpringBatchEndpoint batchEndpoint = camelContext.getEndpoint("spring-batch:mockJob", SpringBatchEndpoint.class);
    JobLauncher batchEndpointJobLauncher = (JobLauncher) FieldUtils.readField(batchEndpoint, "jobLauncher", true);
    assertSame(jobLauncher, batchEndpointJobLauncher);
}
项目:Camel    文件:SpringBatchEndpointTest.java   
@Test
public void shouldUseJobLauncherFromComponent() throws Exception {
    // Given
    SpringBatchComponent batchComponent = new SpringBatchComponent();
    batchComponent.setJobLauncher(alternativeJobLauncher);
    context.addComponent("customBatchComponent", batchComponent);

    // When
    context().addRoutes(new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            from("direct:startCustom").to("customBatchComponent:mockJob");
        }
    });

    // Then
    SpringBatchEndpoint batchEndpoint = context().getEndpoint("customBatchComponent:mockJob", SpringBatchEndpoint.class);
    JobLauncher batchEndpointJobLauncher = (JobLauncher) FieldUtils.readField(batchEndpoint, "jobLauncher", true);
    assertSame(alternativeJobLauncher, batchEndpointJobLauncher);
}
项目:kc-rice    文件:KNSLegacyDataAdapterImpl.java   
/**
 * @see ValueHolderFieldPair for information on why we need to do field sychronization related to weaving
 */
private void searchValueHolderFieldPairs(Class<?> type, List<ValueHolderFieldPair> pairs) {
    if (type.equals(Object.class)) {
        return;
    }
    for (Field valueHolderField : type.getDeclaredFields()) {
        Matcher matcher = VALUE_HOLDER_FIELD_PATTERN.matcher(valueHolderField.getName());
        if (matcher.matches()) {
            valueHolderField.setAccessible(true);
            String fieldName = matcher.group(1);
            Field valueField = FieldUtils.getDeclaredField(type, fieldName, true);
            if (valueField != null) {
                pairs.add(new ValueHolderFieldPair(valueField, valueHolderField));
            }
        }
    }
    searchValueHolderFieldPairs(type.getSuperclass(), pairs);
}
项目:openhab-hdl    文件:HomegearClient.java   
/**
 * Parses the device informations into the binding model.
 */
@SuppressWarnings("unchecked")
private HmDevice parseDevice(Map<String, ?> deviceData) throws IllegalAccessException {
    HmDevice device = new HmDevice();

    FieldUtils.writeField(device, "address", deviceData.get("ADDRESS"), true);
    FieldUtils.writeField(device, "type", deviceData.get("TYPE"), true);
    FieldUtils.writeField(device, "hmInterface", HmInterface.HOMEGEAR, true);

    Object[] channelList = (Object[]) deviceData.get("CHANNELS");
    for (int i = 0; i < channelList.length; i++) {
        Map<String, ?> channelData = (Map<String, ?>) channelList[i];
        device.addChannel(parseChannel(device, channelData));
    }

    return device;
}
项目:openhab-hdl    文件:BaseHomematicClient.java   
/**
 * Adds the battery info datapoint to the specified device if the device has
 * batteries.
 */
protected void addBatteryInfo(HmDevice device) throws HomematicClientException {
    HmBattery battery = HmBatteryTypeProvider.getBatteryType(device.getType());
    if (battery != null) {
        for (HmChannel channel : device.getChannels()) {
            if ("0".equals(channel.getNumber())) {
                try {
                    logger.debug("Adding battery type to device {}: {}", device.getType(), battery.getInfo());
                    HmDatapoint dp = new HmDatapoint();
                    FieldUtils.writeField(dp, "name", "BATTERY_TYPE", true);
                    FieldUtils.writeField(dp, "writeable", Boolean.FALSE, true);
                    FieldUtils.writeField(dp, "valueType", 20, true);
                    dp.setValue(battery.getInfo());
                    channel.addDatapoint(dp);
                } catch (IllegalAccessException ex) {
                    throw new HomematicClientException(ex.getMessage(), ex);
                }
            }
        }
    }
}
项目:motech    文件:EntityMetadataBuilderImpl.java   
private void addDefaultFetchGroupMetadata(FieldMetadata fmd, Class<?> definition) {
    java.lang.reflect.Field field = FieldUtils.getField(definition, fmd.getName(), true);

    if (field == null) {
        LOGGER.warn("Unable to retrieve field {} from class {}. Putting the field in the default fetch group by default.",
                fmd.getName(), definition.getName());
        fmd.setDefaultFetchGroup(true);
    } else {
        Persistent persistentAnnotation = ReflectionsUtil.getAnnotationSelfOrAccessor(field, Persistent.class);

        // set to true, unless there is a JDO annotation that specifies otherwise
        if (persistentAnnotation == null || StringUtils.isBlank(persistentAnnotation.defaultFetchGroup())) {
            fmd.setDefaultFetchGroup(true);
        }
    }
}
项目:motech    文件:InstanceServiceImpl.java   
private void validateNonEditableField(FieldRecord fieldRecord, Object instance, Object parsedValue, MetadataDto versionMetadata) throws IllegalAccessException {
    Object fieldOldValue = FieldUtils.readField(instance,
                    StringUtils.uncapitalize(fieldRecord.getName()),
                    true);

    // We need to check if read only field value isn't changed
    // in some unexpected way. If so then throw exception
    if (fieldRecord.isNonEditable()
            // There is need to use Objects.equals as values - one or both - can be null
            // which would cause NullPointerException when just .equals() on null value
            && !Objects.equals(fieldOldValue, parsedValue)) {
        // Skip for version field
        if (versionMetadata != null && Constants.Util.TRUE.equals(versionMetadata.getValue())) {
            return;
        }
        throw new FieldReadOnlyException(instance.getClass().getName(), fieldRecord.getName());
    }
}
项目:community-edition-old    文件:AclTrackerTest.java   
@Test
public void checkTrackingWhenAclChangeSetsToPurge() throws IllegalAccessException, IOException
{
    @SuppressWarnings("unchecked")
    ConcurrentLinkedQueue<Long> aclChangeSetsToPurge = (ConcurrentLinkedQueue<Long>)
    FieldUtils.readField(tracker, "aclChangeSetsToPurge", true);
    aclChangeSetsToPurge.add(101L);
    aclChangeSetsToPurge.add(102L);
    aclChangeSetsToPurge.add(103L);

    // Invoke the behaviour we're testing
    testTrackChangesRan();

    // aclChangeSetsToPurge
    verify(informationServer).deleteByAclChangeSetId(101L);
    verify(informationServer).deleteByAclChangeSetId(102L);
    verify(informationServer).deleteByAclChangeSetId(103L);

    // TODO: verify checkShutdown
    verify(informationServer).commit();
}
项目:community-edition-old    文件:AclTrackerTest.java   
@Test
public void checkTrackingWhenAclsToPurge() throws IllegalAccessException, IOException
{
    @SuppressWarnings("unchecked")
    ConcurrentLinkedQueue<Long> aclsToPurge = (ConcurrentLinkedQueue<Long>)
    FieldUtils.readField(tracker, "aclsToPurge", true);
    aclsToPurge.add(201L);
    aclsToPurge.add(202L);
    aclsToPurge.add(203L);

    // Invoke the behaviour we're testing
    testTrackChangesRan();

    // aclsToPurge
    verify(informationServer).deleteByAclId(201L);
    verify(informationServer).deleteByAclId(202L);
    verify(informationServer).deleteByAclId(203L);

    // TODO: verify checkShutdown
    verify(informationServer).commit();
}
项目:community-edition-old    文件:AclTrackerTest.java   
@Test
public void trackingAbortsWhenAlreadyRunning() throws Throwable
{
    trackerState.setRunning(true);
    // Prove running state, before attempt to track()
    assertTrue(trackerState.isRunning());

    FieldUtils.writeField(tracker, "state", trackerState, true);
    tracker.track();

    // Still running - these values are unaffected.
    assertTrue(trackerState.isRunning());
    assertFalse(trackerState.isCheck());

    // Prove doTrack() was not called
    verify(tracker, never()).doTrack();
}
项目:rice    文件:KNSLegacyDataAdapterImpl.java   
/**
 * @see ValueHolderFieldPair for information on why we need to do field sychronization related to weaving
 */
private void searchValueHolderFieldPairs(Class<?> type, List<ValueHolderFieldPair> pairs) {
    if (type.equals(Object.class)) {
        return;
    }
    for (Field valueHolderField : type.getDeclaredFields()) {
        Matcher matcher = VALUE_HOLDER_FIELD_PATTERN.matcher(valueHolderField.getName());
        if (matcher.matches()) {
            valueHolderField.setAccessible(true);
            String fieldName = matcher.group(1);
            Field valueField = FieldUtils.getDeclaredField(type, fieldName, true);
            if (valueField != null) {
                pairs.add(new ValueHolderFieldPair(valueField, valueHolderField));
            }
        }
    }
    searchValueHolderFieldPairs(type.getSuperclass(), pairs);
}
项目:docker-java    文件:ModelsSerializableTest.java   
@Test
public void allModelsSerializable() throws IOException, NoSuchFieldException, IllegalAccessException {
    final ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
    for (ClassInfo classInfo : from(contextClassLoader).getTopLevelClasses("com.github.dockerjava.api.model")) {
        if (classInfo.getName().endsWith("Test")) {
            continue;
        }

        final Class<?> aClass = classInfo.load();
        if (aClass.getProtectionDomain().getCodeSource().getLocation().getPath().endsWith("test-classes/")
                || aClass.isEnum()) {
            continue;
        }

        LOG.debug("aClass: {}", aClass);
        assertThat(aClass, typeCompatibleWith(Serializable.class));

        final Object serialVersionUID = FieldUtils.readDeclaredStaticField(aClass, "serialVersionUID", true);
        if (!excludeClasses.contains(aClass.getName())) {
            assertThat(serialVersionUID, instanceOf(Long.class));
            assertThat("Follow devel docs", (Long) serialVersionUID, is(1L));
        }
    }
}
项目:pinot    文件:ObjectSeries.java   
private static Object mapExpression(List<String> expressions, Object value) throws Exception {
  if(expressions.isEmpty())
    return value;

  String head = expressions.get(0);
  List<String> tail = expressions.subList(1, expressions.size());

  if(head.equals("this"))
    return mapExpression(tail, value);

  if(head.endsWith("()")) {
    head = head.substring(0, head.length() - 2);
    // method call
    return mapExpression(tail, invokeMethod(value, head));

  } else {
    // field access
    return mapExpression(tail, FieldUtils.readField(value, head, true));
  }
}
项目:pom-manipulation-ext    文件:CliTest.java   
@Test
public void checkLocalRepositoryWithDefaults() throws Exception
{
    Cli c = new Cli();
    File settings = writeSettings( temp.newFile());

    executeMethod( c, "run", new Object[] { new String[] { "-s", settings.toString()} } );

    ManipulationSession session = (ManipulationSession) FieldUtils.readField( c, "session", true );
    MavenSession ms = (MavenSession)FieldUtils.readField( session, "mavenSession", true );

    assertTrue( ms.getRequest().getLocalRepository().getBasedir().equals( ms.getRequest().getLocalRepositoryPath().toString() ) );
    assertTrue ( "File " + new File ( ms.getRequest().getLocalRepository().getBasedir() ).getParentFile().toString() +
                                 " was not equal to " + System.getProperty( "user.home" ) + File.separatorChar + ".m2",
                    new File ( ms.getRequest().getLocalRepository().getBasedir() ).getParentFile().toString().
                    equals( System.getProperty( "user.home" ) + File.separatorChar + ".m2" ) );

}
项目:pom-manipulation-ext    文件:DistributionEnforcingManipulatorTest.java   
@Before
public void before()
    throws Exception
{
    userCliProperties = new Properties();
    session = new ManipulationSession();

    final GalleyInfrastructure galleyInfra =
        new GalleyInfrastructure( session.getTargetDir(), session.getRemoteRepositories(),
                        session.getLocalRepository(), session.getSettings(), session.getActiveProfiles(),
                        null, null, null, temp.newFolder( "cache-dir" ) );

    final GalleyAPIWrapper wrapper = new GalleyAPIWrapper( galleyInfra );

    manipulator = new DistributionEnforcingManipulator( );
    FieldUtils.writeField (manipulator, "galleyWrapper", wrapper, true);
}
项目:pom-manipulation-ext    文件:ModelResolverTest.java   
@Test(expected = ManipulationException.class)
@BMRule(name = "retrieve-first-null",
                targetClass = "ArtifactManagerImpl",
                targetMethod = "retrieveFirst(List<? extends Location> locations, ArtifactRef ref)",
                targetLocation = "AT ENTRY",
                action = "RETURN null"
)
public void resolveArtifactTest()
    throws Exception
{
    final ManipulationSession session = new ManipulationSession();
    final GalleyInfrastructure galleyInfra =
        new GalleyInfrastructure( session.getTargetDir(), session.getRemoteRepositories(), session.getLocalRepository(),
                                  session.getSettings(), session.getActiveProfiles(), null, null, null, temp.newFolder(
                        "cache-dir" ) );
    final GalleyAPIWrapper wrapper = new GalleyAPIWrapper( galleyInfra );
    final ModelIO model = new ModelIO();
    FieldUtils.writeField( model, "galleyWrapper", wrapper, true );

    model.resolveRawModel( SimpleProjectVersionRef.parse( "org.commonjava:commonjava:5"  ) );
}
项目:openhab1-addons    文件:HomegearClient.java   
/**
 * Parses the device informations into the binding model.
 */
@SuppressWarnings("unchecked")
private HmDevice parseDevice(Map<String, ?> deviceData) throws IllegalAccessException {
    HmDevice device = new HmDevice();

    FieldUtils.writeField(device, "address", deviceData.get("ADDRESS"), true);
    FieldUtils.writeField(device, "type", deviceData.get("TYPE"), true);
    FieldUtils.writeField(device, "hmInterface", HmInterface.HOMEGEAR, true);

    Object[] channelList = (Object[]) deviceData.get("CHANNELS");
    for (int i = 0; i < channelList.length; i++) {
        Map<String, ?> channelData = (Map<String, ?>) channelList[i];
        device.addChannel(parseChannel(device, channelData));
    }

    return device;
}
项目:openhab1-addons    文件:BaseHomematicClient.java   
/**
 * Adds the battery info datapoint to the specified device if the device has
 * batteries.
 */
protected void addBatteryInfo(HmDevice device) throws HomematicClientException {
    HmBattery battery = HmBatteryTypeProvider.getBatteryType(device.getType());
    if (battery != null) {
        for (HmChannel channel : device.getChannels()) {
            if ("0".equals(channel.getNumber())) {
                try {
                    logger.debug("Adding battery type to device {}: {}", device.getType(), battery.getInfo());
                    HmDatapoint dp = new HmDatapoint();
                    FieldUtils.writeField(dp, "name", "BATTERY_TYPE", true);
                    FieldUtils.writeField(dp, "writeable", Boolean.FALSE, true);
                    FieldUtils.writeField(dp, "valueType", 20, true);
                    dp.setValue(battery.getInfo());
                    channel.addDatapoint(dp);
                } catch (IllegalAccessException ex) {
                    throw new HomematicClientException(ex.getMessage(), ex);
                }
            }
        }
    }
}
项目:usergrid    文件:Schema.java   
private <T extends Annotation> T getAnnotation( Class<? extends Entity> entityClass, PropertyDescriptor descriptor,
                                                Class<T> annotationClass ) {
    try {
        if ( ( descriptor.getReadMethod() != null ) && descriptor.getReadMethod()
                                                                 .isAnnotationPresent( annotationClass ) ) {
            return descriptor.getReadMethod().getAnnotation( annotationClass );
        }
        if ( ( descriptor.getWriteMethod() != null ) && descriptor.getWriteMethod()
                                                                  .isAnnotationPresent( annotationClass ) ) {
            return descriptor.getWriteMethod().getAnnotation( annotationClass );
        }
        Field field = FieldUtils.getField( entityClass, descriptor.getName(), true );
        if ( field != null ) {
            if ( field.isAnnotationPresent( annotationClass ) ) {
                return field.getAnnotation( annotationClass );
            }
        }
    }
    catch ( Exception e ) {
        logger.error( "Could not retrieve the annotations", e );
    }
    return null;
}
项目:java-presentation-manager-2    文件:Field.java   
/**
 * Finds the current field class.
 *
 * @param baseClass
 * @return
 */
public Class getClass(String baseClass) {
    try {
        final String _property = getProperty();
        final String[] _properties = _property.split("[.]");
        Class<?> clazz = Class.forName(baseClass);
        for (int i = 0; i < _properties.length - 1; i++) {
            clazz = FieldUtils.getField(clazz, _properties[i], true).getType();
        }
        final String className = FieldUtils.getField(clazz, _properties[_properties.length - 1], true).getType().getName();
        return Class.forName(className);
    } catch (ClassNotFoundException ex) {
        JPMUtils.getLogger().error(ex);
    }
    return null;
}
项目:carewebframework-core    文件:CWFUtil.java   
/**
 * Wires variables from a map into a controller. Useful to inject parameters passed in an
 * argument map.
 *
 * @param map The argument map.
 * @param controller The controller to be wired.
 */
public static void wireController(Map<?, ?> map, Object controller) {
    if (map == null || map.isEmpty() || controller == null) {
        return;
    }

    for (Entry<?, ?> entry : map.entrySet()) {
        String key = entry.getKey().toString();
        Object value = entry.getValue();

        try {
            PropertyUtils.setProperty(controller, key, value);
        } catch (Exception e) {
            try {
                FieldUtils.writeField(controller, key, value, true);
            } catch (Exception e1) {}
        }

    }
}
项目:pentaho-kettle    文件:ConnectionsControllerTest.java   
@Before
public void setUp() throws Exception {
  // a tricky initialisation - first inject private fields
  controller = new ConnectionsController();
  connectionsTable = mock( XulTree.class );
  FieldUtils.writeDeclaredField( controller, "connectionsTable", connectionsTable, true );

  // and then spy the controller
  controller = spy( controller );

  databaseDialog = mock( DatabaseDialog.class );
  doReturn( databaseDialog ).when( controller ).getDatabaseDialog();
  databaseMeta = mock( DatabaseMeta.class );
  doReturn( databaseMeta ).when( databaseDialog ).getDatabaseMeta();
  doNothing().when( controller ).refreshConnectionList();
  doNothing().when( controller ).showAlreadyExistsMessage();

  repository = mock( Repository.class );
  controller.init( repository );
}
项目:pentaho-kettle    文件:SFTPPutDialogTest.java   
@BeforeClass
public static void hackPropsUi() throws Exception {
  Field props = getPropsField();
  if ( props == null ) {
    throw new IllegalStateException( "Cannot find 'props' field in " + Props.class.getName() );
  }

  Object value = FieldUtils.readStaticField( props, true );
  if ( value == null ) {
    PropsUI mock = mock( PropsUI.class );
    FieldUtils.writeStaticField( props, mock, true );
    changedPropsUi = true;
  } else {
    changedPropsUi = false;
  }
}
项目:pentaho-kettle    文件:TextFileInputDialogTest.java   
@BeforeClass
public static void hackPropsUi() throws Exception {
  Field props = getPropsField();
  if ( props == null ) {
    throw new IllegalStateException( "Cannot find 'props' field in " + Props.class.getName() );
  }

  Object value = FieldUtils.readStaticField( props, true );
  if ( value == null ) {
    PropsUI mock = mock( PropsUI.class );
    FieldUtils.writeStaticField( props, mock, true );
    changedPropsUi = true;
  } else {
    changedPropsUi = false;
  }
}
项目:pentaho-kettle    文件:PurRepository_GetObjectInformation_IT.java   
private void testDeletedFlagForObject( Callable<RepositoryElementInterface> elementProvider ) throws Exception {
  TransDelegate transDelegate = new TransDelegate( purRepository, unifiedRepository );
  JobDelegate jobDelegate = new JobDelegate( purRepository, unifiedRepository );
  FieldUtils.writeField( purRepository, "transDelegate", transDelegate, true );
  FieldUtils.writeField( purRepository, "jobDelegate", jobDelegate, true );

  RepositoryElementInterface element = elementProvider.call();
  RepositoryDirectoryInterface directory = purRepository.findDirectory( element.getRepositoryDirectory().getPath() );
  element.setRepositoryDirectory( directory );

  purRepository.save( element, null, null );
  assertNotNull( "Element was saved", element.getObjectId() );

  RepositoryObject information;
  information = purRepository.getObjectInformation( element.getObjectId(), element.getRepositoryElementType() );
  assertNotNull( information );
  assertFalse( information.isDeleted() );

  purRepository.deleteTransformation( element.getObjectId() );
  assertNotNull( "Element was moved to Trash", unifiedRepository.getFileById( element.getObjectId().getId() ) );

  information = purRepository.getObjectInformation( element.getObjectId(), element.getRepositoryElementType() );
  assertNotNull( information );
  assertTrue( information.isDeleted() );
}
项目:alfresco-repository    文件:StandardQuotaStrategyMockTest.java   
@Test
public void testCanSetMaxUsageInMB() throws IllegalAccessException
{
    quota.setMaxUsageMB(0);
    assertEquals(0, ((Long) FieldUtils.readDeclaredField(quota, "maxUsageBytes", true)).longValue());

    quota.setMaxUsageMB(500);
    assertEquals(524288000, ((Long) FieldUtils.readDeclaredField(quota, "maxUsageBytes", true)).longValue());

    // 1 GB
    quota.setMaxUsageMB(1024);
    assertEquals(1073741824, ((Long) FieldUtils.readDeclaredField(quota, "maxUsageBytes", true)).longValue());
}
项目:atlas    文件:TransformManager.java   
public static void replaceTransformTask(TransformTask transformTask,
                                        Transform newTransform) {

    Field transfromField = FieldUtils.getDeclaredField(TransformTask.class,
                                                       "transform",
                                                       true);
    if (null != transfromField) {
        try {
            transfromField.set(transformTask, newTransform);
        } catch (IllegalAccessException e) {
            throw new GradleException(e.getMessage(), e);
        }
    }
}
项目:Mycat-Demo    文件:ReflectHelper.java   
public static Object getFieldValue(Object obj , String fieldName ){  

    if(obj == null){  
        return null ;  
    }  

    Field targetField = getTargetField(obj.getClass(), fieldName);  

    try {  
        return FieldUtils.readField(targetField, obj, true ) ;  
    } catch (IllegalAccessException e) {  
        e.printStackTrace();  
    }   
    return null ;  
}
项目:Mycat-Demo    文件:ReflectHelper.java   
public static void setFieldValue(Object obj , String fieldName , Object value ){  
    if(null == obj){return;}  
    Field targetField = getTargetField(obj.getClass(), fieldName);    
    try {  
         FieldUtils.writeField(targetField, obj, value) ;  
    } catch (IllegalAccessException e) {  
        e.printStackTrace();  
    }   
}
项目:leopard    文件:FieldUtil.java   
public static Object getFieldValue(Object bean, String fieldName) {
    Field field = FieldUtils.getField(bean.getClass(), fieldName, true);
    if (field == null) {
        throw new NullPointerException("在对象[" + bean.getClass().getName() + "]找不到属性[" + fieldName + "].");
    }
    return getFieldValue(bean, field);
}
项目:leopard    文件:FieldUtil.java   
public static Object getFieldValue(Object bean, String fieldName) {
    Field field = FieldUtils.getField(bean.getClass(), fieldName, true);
    if (field == null) {
        throw new NullPointerException("在对象[" + bean.getClass().getName() + "]找不到属性[" + fieldName + "].");
    }
    return getFieldValue(bean, field);
}
项目:mojito    文件:QualityCheckStep.java   
/**
 * Initializes the QualityCheckSession defined in the parent step, using Reflection
 */
public QualityCheckStep() {
    super();

    try {
        parentSession = new QualityCheckSession();

        // replace the "session" with our own version
        Field field = FieldUtils.getDeclaredField(this.getClass().getSuperclass(), "session", true);
        field.set(this, parentSession);
    } catch (IllegalAccessException e) {
        logger.error("Cannot replace the QualityCheckSession with Reflection");
    }
}
项目:org.ops4j.ramler    文件:SimpleObjectTest.java   
@SuppressWarnings("unchecked")
@Test
public void shouldFindEnumValues() throws IllegalAccessException {
    klass = modelPackage._getClass("Colour");
    assertThat(klass.getClassType()).isEqualTo(ClassType.ENUM);
    Map<String,JEnumConstant> enums = (Map<String, JEnumConstant>) FieldUtils.readField(klass, "enumConstantsByName", true);
    assertThat(enums.keySet()).containsExactly("LIGHT_BLUE", "RED", "YELLOW", "GREEN");
}
项目:cuba    文件:BaseEntityInternalAccess.java   
public static void setValue(Entity entity, String attribute, @Nullable Object value) {
    Preconditions.checkNotNullArgument(entity, "entity is null");
    Field field = FieldUtils.getField(entity.getClass(), attribute, true);
    if (field == null)
        throw new RuntimeException(String.format("Cannot find field '%s' in class %s", attribute, entity.getClass().getName()));
    try {
        field.set(entity, value);
    } catch (IllegalAccessException e) {
        throw new RuntimeException(String.format("Unable to set value to %s.%s", entity.getClass().getSimpleName(), attribute), e);
    }
}
项目:cuba    文件:BaseEntityInternalAccess.java   
public static void setValueForHolder(Entity entity, String attribute, @Nullable Object value) {
    Preconditions.checkNotNullArgument(entity, "entity is null");
    Field field = FieldUtils.getField(entity.getClass(), String.format("_persistence_%s_vh",attribute), true);
    if (field == null)
        return;
    try {
        field.set(entity, value);
    } catch (IllegalAccessException e) {
        throw new RuntimeException(String.format("Unable to set value to %s.%s", entity.getClass().getSimpleName(), attribute), e);
    }
}