Example usage for org.apache.commons.lang3.reflect FieldUtils readField

List of usage examples for org.apache.commons.lang3.reflect FieldUtils readField

Introduction

In this page you can find the example usage for org.apache.commons.lang3.reflect FieldUtils readField.

Prototype

public static Object readField(final Object target, final String fieldName, final boolean forceAccess)
        throws IllegalAccessException 

Source Link

Document

Reads the named Field .

Usage

From source file:com.github.rutledgepaulv.qbuilders.visitors.PredicateVisitor.java

private Object getFieldValueFromString(Object o, String s) {
    if (o == null) {
        return null;
    }//  ww w.ja  v a2  s  .c  om
    try {
        return FieldUtils.readField(o, s, true);
    } catch (IllegalAccessException e) {
        return null;
    }
}

From source file:com.astamuse.asta4d.data.InjectUtil.java

/**
 * Retrieve values from fields marked as reverse injectable of given instance.
 * /*from  ww w. ja va  2s.  c  o  m*/
 * There are only limited scopes can be marked as injectable. See {@link Configuration#setReverseInjectableScopes(List)}.
 * 
 * NOT SUPPORTED ANY MORE!!!
 * 
 * @param instance
 * @throws DataOperationException
 */
@Deprecated
public final static void setContextDataFromInstance(Object instance) throws DataOperationException {
    try {
        Context context = Context.getCurrentThreadContext();
        InstanceWireTarget target = getInstanceTarget(instance);
        Object value;
        for (FieldInfo fi : target.getFieldList) {
            value = FieldUtils.readField(fi.field, instance, true);
            context.setData(fi.scope, fi.name, value);
        }

        for (MethodInfo mi : target.getMethodList) {
            value = mi.method.invoke(instance);
            context.setData(mi.scope, mi.name, value);
        }
    } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
        String msg = String.format("Exception when inject value from instance of [%s] to Context.",
                instance.getClass().toString());
        throw new DataOperationException(msg, e);
    }
}

From source file:com.android.builder.core.AtlasAapt.java

@Override
protected ProcessInfoBuilder makePackageProcessBuilder(AaptPackageConfig config) throws AaptException {
    ProcessInfoBuilder processInfoBuilder = super.makePackageProcessBuilder(config);

    List<String> args = null;
    try {/*  www .  jav a  2  s. c  o m*/
        args = (List<String>) FieldUtils.readField(processInfoBuilder, "mArgs", true);
    } catch (IllegalAccessException e) {
        throw new GradleException("getargs exception", e);
    }

    //args.remove("--no-version-vectors");
    //
    ////?? manifest_keep.txt 
    //int indexD = args.indexOf("-D");
    //if (indexD > 0){
    //    args.remove(indexD);
    //    args.remove(indexD);
    //}

    //R.txt?
    String sybolOutputDir = config.getSymbolOutputDir().getAbsolutePath();
    if (!args.contains("--output-text-symbols") && null != sybolOutputDir) {
        args.add("--output-text-symbols");
        args.add(sybolOutputDir);
    }

    return processInfoBuilder;
}

From source file:com.offbynull.coroutines.instrumenter.InstrumenterTest.java

@Test
public void mustKeepTrackOfSynchronizedBlocks() throws Exception {
    LinkedList<String> tracker = new LinkedList<>();

    // mon1/mon2/mon3 all point to different objects that are logically equivalent but different objects. Tracking should ignore logical
    // equivallence and instead focus on checking to make sure that they references are the same. We don't want to call MONITOREXIT on
    // the wrong object because it .equals() another object in the list of monitors being tracked.
    Object mon1 = new ArrayList<>();
    Object mon2 = new ArrayList<>();
    Object mon3 = new ArrayList<>();

    // All we're testing here is tracking. It's difficult to test to see if monitors were re-entered/exited.
    try (URLClassLoader classLoader = loadClassesInZipResourceAndInstrument(MONITOR_INVOKE_TEST + ".zip")) {
        Class<Coroutine> cls = (Class<Coroutine>) classLoader.loadClass(MONITOR_INVOKE_TEST);
        Coroutine coroutine = ConstructorUtils.invokeConstructor(cls, tracker, mon1, mon2, mon3);

        CoroutineRunner runner = new CoroutineRunner(coroutine);

        // get continuation object so that we can inspect it and make sure its lockstate is what we expect
        Continuation continuation = (Continuation) FieldUtils.readField(runner, "continuation", true);

        Assert.assertTrue(runner.execute());
        Assert.assertEquals(Arrays.asList("mon1", "mon2", "mon3", "mon1"), tracker);
        Assert.assertArrayEquals(new Object[] { mon1 }, continuation.getSaved(0).getLockState().toArray());
        Assert.assertArrayEquals(new Object[] { mon2, mon3, mon1 },
                continuation.getSaved(1).getLockState().toArray());

        Assert.assertTrue(runner.execute());
        Assert.assertEquals(Arrays.asList("mon1", "mon2", "mon3"), tracker);
        Assert.assertArrayEquals(new Object[] { mon1 }, continuation.getSaved(0).getLockState().toArray());
        Assert.assertArrayEquals(new Object[] { mon2, mon3 },
                continuation.getSaved(1).getLockState().toArray());

        Assert.assertTrue(runner.execute());
        Assert.assertEquals(Arrays.asList("mon1", "mon2"), tracker);
        Assert.assertArrayEquals(new Object[] { mon1 }, continuation.getSaved(0).getLockState().toArray());
        Assert.assertArrayEquals(new Object[] { mon2 }, continuation.getSaved(1).getLockState().toArray());

        Assert.assertTrue(runner.execute());
        Assert.assertEquals(Arrays.asList("mon1"), tracker);
        Assert.assertArrayEquals(new Object[] { mon1 }, continuation.getSaved(0).getLockState().toArray());
        Assert.assertArrayEquals(new Object[] {}, continuation.getSaved(1).getLockState().toArray());

        Assert.assertTrue(runner.execute());
        Assert.assertEquals(Arrays.<String>asList(), tracker);
        Assert.assertArrayEquals(new Object[] {}, continuation.getSaved(0).getLockState().toArray());

        Assert.assertFalse(runner.execute()); // coroutine finished executing here            
    }//from ww  w  . java 2  s .  co  m
}

From source file:com.android.builder.core.AtlasBuilder.java

@Override
public void processResources(Aapt aapt, Builder aaptConfigBuilder, boolean enforceUniquePackageName)
        throws IOException, InterruptedException, ProcessException {

    if (aapt instanceof AaptV1) {
        try {//from  w ww . j a va  2 s .  c o  m

            getTargetInfo();

            AaptOptions aaptOptions = (AaptOptions) FieldUtils.readField(aaptConfigBuilder.build(),
                    "mAaptOptions", true);

            ProcessExecutor processExecutor = (ProcessExecutor) FieldUtils.readField(aapt, "mProcessExecutor",
                    true);
            ProcessOutputHandler processOutputHandler = (ProcessOutputHandler) FieldUtils.readField(aapt,
                    "mProcessOutputHandler", true);
            BuildToolInfo buildToolInfo = (BuildToolInfo) FieldUtils.readField(aapt, "mBuildToolInfo", true);
            PngProcessMode processMode = (PngProcessMode) FieldUtils.readField(aapt, "mProcessMode", true);
            int cruncherProcesses = aaptOptions.getCruncherProcesses();

            aapt = new AtlasAapt(processExecutor, processOutputHandler, buildToolInfo, getLogger(), processMode,
                    cruncherProcesses);
        } catch (Throwable e) {
            throw new GradleException("aapt exception", e);
        }
    }

    super.processResources(aapt, aaptConfigBuilder, enforceUniquePackageName);
}

From source file:com.holonplatform.core.internal.beans.DefaultBeanPropertySet.java

/**
 * Read the <code>property</code> value from given instance (if not null), using BeanProperty configuration read
 * method or field, if available.//from ww w.  j  a  v  a 2 s. c  o  m
 * @param property Property to read
 * @param instance Instance to read from
 * @return Property value
 */
private static Object readValue(BeanProperty<?> property, Object instance) {

    ObjectUtils.argumentNotNull(property, "Property must be not null");

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

    final Object value;

    if (property.getReadMethod().isPresent()) {
        try {
            value = property.getReadMethod().get().invoke(instance);

            LOGGER.debug(() -> "BeanPropertySet: read property [" + property + "] value [" + value
                    + "] from instance [" + instance + "] using method [" + property.getReadMethod() + "]");

        } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
            throw new PropertyReadException(property, "Failed to read bean property [" + property
                    + "] from instance [" + instance + "] using method [" + property.getReadMethod() + "]", e);
        }
    } else {
        Field field = property.getField()
                .orElseThrow(() -> new PropertyReadException(property,
                        "No read method and no accessible field available to read property [" + property
                                + "] on bean class [" + instance.getClass().getName() + "]"));
        try {
            value = FieldUtils.readField(field, instance, true);

            LOGGER.debug(() -> "BeanPropertySet: read property [" + property + "] value [" + value
                    + "] from instance [" + instance + "] using field [" + field + "]");

        } catch (IllegalAccessException e) {
            throw new PropertyReadException(property, "Failed to read bean property [" + property
                    + "] from instance [" + instance + "] using field [" + field + "]", e);
        }

    }

    return value;

}

From source file:com.thinkbiganalytics.spark.datavalidator.Validator.java

/**
 * Extract the @PolicyProperty annotated fields
 *
 * @param policy the policy (validator or standardizer to parse)
 * @return a string of the fileds and values
 *//*w w  w .  jav  a 2 s  .  c  om*/
private String getFieldPolicyDetails(BaseFieldPolicy policy) {
    //cache the list
    AnnotationFieldNameResolver annotationFieldNameResolver = new AnnotationFieldNameResolver(
            PolicyProperty.class);
    List<AnnotatedFieldProperty> list = annotationFieldNameResolver.getProperties(policy.getClass());
    StringBuffer sb = null;
    for (AnnotatedFieldProperty<PolicyProperty> annotatedFieldProperty : list) {
        PolicyProperty prop = annotatedFieldProperty.getAnnotation();
        String value = null;
        if (sb != null) {
            sb.append(",");
        }
        if (sb == null) {
            sb = new StringBuffer();
        }
        sb.append(StringUtils.isBlank(prop.displayName()) ? prop.name() : prop.displayName());

        try {
            Object fieldValue = FieldUtils.readField(annotatedFieldProperty.getField(), policy, true);
            if (fieldValue != null) {
                value = fieldValue.toString();
            }
        } catch (IllegalAccessException e) {

        }
        sb.append(" = ");
        sb.append(value == null ? "<null> " : value);
    }
    return sb != null ? sb.toString() : "";
}

From source file:jdao.JDAO.java

public static <T> Map<String, Object> extractIdKvFromBean(Object _bean, Class<T> _beanClazz) {
    Map<String, Object> _ret = new HashMap();
    List<Field> fields = FieldUtils.getFieldsListWithAnnotation(_beanClazz, IBeanID.class);
    if (fields.size() > 0) {
        throw new IllegalArgumentException("improper IBeanID annotation");
    }//from   w  ww  .j  a  v  a  2s.co  m
    try {
        Iterator<Field> it = fields.iterator();
        while (it.hasNext()) {
            Field field = it.next();
            String _key = field.getAnnotation(IBeanField.class).value();
            Object _val = FieldUtils.readField(field, _bean, true);
            _ret.put(_key, _val);
        }
        return _ret;
    } catch (IllegalAccessException e) {
        // IGNORE
    }
    return null;
}

From source file:jdao.JDAO.java

public static <T> Map<String, Object> extractColsFromBean(Object _bean, Class<T> _beanClazz,
        boolean _inclIdField) {
    Map<String, Object> _ret = new HashMap();
    List<Field> fields = FieldUtils.getFieldsListWithAnnotation(_beanClazz, IBeanField.class);
    for (Field field : fields) {
        try {/*from   w  w w  .j a v a2  s .  c  o  m*/
            if (_inclIdField || (!field.isAnnotationPresent(IBeanID.class))) {
                String _key = field.getAnnotation(IBeanField.class).value();
                Object _val = FieldUtils.readField(field, _bean, true);
                _ret.put(_key, _val);
            }
        } catch (IllegalAccessException e) {
            // IGNORE
        }
    }
    return _ret;
}

From source file:net.sourceforge.pmd.util.fxdesigner.util.controls.TreeViewWrapper.java

private static Object getVirtualFlow(Skin<?> skin) {
    try {/* w  w w. j ava  2 s  .c o m*/
        // On JRE 9 and 10, the field is declared in TreeViewSkin
        // http://hg.openjdk.java.net/openjfx/9/rt/file/c734b008e3e8/modules/javafx.controls/src/main/java/javafx/scene/control/skin/TreeViewSkin.java#l85
        // http://hg.openjdk.java.net/openjfx/10/rt/file/d14b61c6be12/modules/javafx.controls/src/main/java/javafx/scene/control/skin/TreeViewSkin.java#l85
        // On JRE 8, the field is declared in the VirtualContainerBase superclass
        // http://hg.openjdk.java.net/openjfx/8/master/rt/file/f89b7dc932af/modules/controls/src/main/java/com/sun/javafx/scene/control/skin/VirtualContainerBase.java#l68

        return FieldUtils.readField(skin, "flow", true);
    } catch (IllegalAccessException ignored) {

    }
    return null;
}