Example usage for java.lang.reflect Field setAccessible

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

Introduction

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

Prototype

@Override
@CallerSensitive
public void setAccessible(boolean flag) 

Source Link

Usage

From source file:bdi4jade.util.ReflectionUtils.java

/**
 * Sets plan body fields annotated with {@link bdi4jade.annotation.Belief}.
 * /*from   w  w w . ja v  a2s.c om*/
 * @param planBody
 *            the plan body to be setup with beliefs.
 */
public static void setupBeliefs(PlanBody planBody) {
    Capability capability = planBody.getPlan().getPlanLibrary().getCapability();
    Class<?> currentClass = planBody.getClass();
    while (PlanBody.class.isAssignableFrom(currentClass)) {
        for (Field field : currentClass.getDeclaredFields()) {
            boolean b = field.isAccessible();
            field.setAccessible(true);
            try {
                if (field.isAnnotationPresent(bdi4jade.annotation.Belief.class)) {
                    if (Belief.class.isAssignableFrom(field.getType())) {
                        bdi4jade.annotation.Belief beliefAnnotation = field
                                .getAnnotation(bdi4jade.annotation.Belief.class);
                        String beliefName = beliefAnnotation.name();
                        if (beliefName == null || "".equals(beliefName)) {
                            beliefName = field.getName();
                        }
                        Belief<?, ?> belief = capability.getBeliefBase().getBelief(beliefName);
                        field.set(planBody, belief);
                    } else {
                        throw new ClassCastException("Field " + field.getName() + " should be a Belief");
                    }
                }
            } catch (Exception exc) {
                log.warn(exc);
            }
            field.setAccessible(b);
        }
        currentClass = currentClass.getSuperclass();
    }
}

From source file:ml.shifu.shifu.util.ClassUtils.java

private static Object getFieldValue(Field field, Object instance)
        throws IllegalArgumentException, IllegalAccessException {
    field.setAccessible(true);
    return field.get(instance);
}

From source file:lite.flow.runtime.kiss.ComponentUtil.java

public static void injectOutput(String outputName, Output<?> output, Object componentInstance)
        throws IllegalArgumentException, IllegalAccessException {

    Class<?> componentClazz = componentInstance.getClass();

    // find activity all Output type fields
    for (Field field : FieldUtils.getAllFields(componentClazz)) {
        Class<?> decl = field.getType();
        if (Output.class.isAssignableFrom(decl)) {

            String name = field.getName();
            if (name != null && name.equals(outputName)) {
                field.setAccessible(true);
                field.set(componentInstance, output);
                return;
            }//from www  .ja va  2  s . com
        }
    }

    throw new IllegalArgumentException(
            format("Class '%s' do not contain output '%s'", componentClazz.getName(), outputName));
}

From source file:lt.emasina.resthub.server.factory.MetadataFactory.java

public static void injectPrivateField(Object o, Class<?> fieldHolderClass, String fieldName, Object value)
        throws Exception {
    Field fResourceMd = fieldHolderClass.getDeclaredField(fieldName);
    fResourceMd.setAccessible(true);
    fResourceMd.set(o, value);//from   w  w  w  . ja  v  a 2s  . co  m
}

From source file:edu.umd.cs.marmoset.utilities.MarmosetUtilities.java

/**
 * Uses reflection to extract the pid, a private field of the private class UNIXProcess.
 * This will fail on any non-Unix platform that doesn't use UNIXProcess.  It may
 * fail if the UNIXProcess class changes at all.  It may fail anyway for unpredictable
 * reasons.//  w w  w .j  a v  a 2 s.  c  om
 * @param process The process
 * @return the pid of this process
 */
public static int getPid(Process process) {
    try {
        Class<? extends Process> processClass = process.getClass();
        Field pidField = processClass.getDeclaredField("pid");
        pidField.setAccessible(true);
        return pidField.getInt(process);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:org.eclipse.virgo.ide.runtime.core.ServerUtils.java

/**
 * Returns the {@link JavaVersion} of the given {@link IJavaProject}
 */// w w w  . java2  s  .c om
public static JavaVersion getJavaVersion(IProject project) {
    IJavaProject javaProject = JdtUtils.getJavaProject(project);
    if (javaProject != null) {

        // first check the manifest for that
        // Bundle-RequiredExecutionEnvironment
        BundleManifest bundleManifest = BundleManifestCorePlugin.getBundleManifestManager()
                .getBundleManifest(javaProject);
        Dictionary<String, String> manifest = bundleManifest.toDictionary();
        if (manifest != null && manifest.get(Constants.BUNDLE_REQUIREDEXECUTIONENVIRONMENT) != null) {
            String javaVersion = manifest.get(Constants.BUNDLE_REQUIREDEXECUTIONENVIRONMENT);
            return JAVA_VERSION_MAPPING.get(javaVersion);
        }

        // second check the project for a matching jvm
        try {
            IClasspathContainer container = JavaCore.getClasspathContainer(JRE_CONTAINER_PATH, javaProject);
            if (container != null && container instanceof JREContainer) {
                // reflection hack to get the internal jvm install
                Field field = JREContainer.class.getDeclaredField("fVMInstall");
                field.setAccessible(true);
                IVMInstall vm = (IVMInstall) field.get((JREContainer) container);

                IExecutionEnvironmentsManager manager = JavaRuntime.getExecutionEnvironmentsManager();
                // check for strict match
                for (IExecutionEnvironment executionEnvironment : manager.getExecutionEnvironments()) {
                    if (executionEnvironment.isStrictlyCompatible(vm)) {
                        return JAVA_VERSION_MAPPING.get(executionEnvironment.getId());
                    }
                }

                // check for default
                for (IExecutionEnvironment executionEnvironment : manager.getExecutionEnvironments()) {
                    if (executionEnvironment.getDefaultVM() != null
                            && executionEnvironment.getDefaultVM().equals(vm)) {
                        return JAVA_VERSION_MAPPING.get(executionEnvironment.getId());
                    }
                }

                // check for compatibility
                for (IExecutionEnvironment executionEnvironment : manager.getExecutionEnvironments()) {
                    if (Arrays.asList(executionEnvironment.getCompatibleVMs()).contains(vm)) {
                        return JAVA_VERSION_MAPPING.get(executionEnvironment.getId());
                    }
                }
            }
        } catch (Exception e) {
            SpringCore.log(e);
        }
    }
    return null;
}

From source file:com.tridion.storage.si4t.JPASearchDAOFactory.java

private static void setPrivateField(final Object fieldOwner, final String fieldName, final Object value,
        Logger log) throws IllegalAccessException {
    final Field privateField = getPrivateFieldRec(fieldOwner.getClass(), fieldName, log);

    if (privateField != null) {

        final boolean accessible = privateField.isAccessible();
        privateField.setAccessible(true);

        privateField.set(fieldOwner, value);

        privateField.setAccessible(accessible);
    }//from ww  w. j av a 2 s. c  o  m
}

From source file:net.ljcomputing.gson.converter.impl.GsonConverterServiceImpl.java

/**
 * Sets the field values./*  ww  w  .  jav a 2s  .  c  om*/
 *
 * @param to the to
 * @param fieldTo the field to
 * @param from the from
 * @param fieldFrom the field from
 * @throws IllegalArgumentException the illegal argument exception
 * @throws IllegalAccessException the illegal access exception
 */
private static void setFieldValues(final Object to, final Field fieldTo, final Object from,
        final Field fieldFrom) throws IllegalArgumentException, IllegalAccessException {
    if (null != fieldTo && null != fieldFrom) {
        fieldTo.setAccessible(true);
        fieldFrom.setAccessible(true);
        fieldTo.set(to, fieldFrom.get(from));
    }
}

From source file:com.titilink.camel.rest.util.CommonUtils.java

/**
 * requestaction?/*from  w  w w  .ja  va 2s  .  co  m*/
 *
 * @param instance
 * @param <T>
 * @throws OperationException
 */
private static <T> void checkActionCount(T instance) throws OperationException {
    if (null == instance) {
        LOGGER.error("checkActionCount FAILED! request is null");
        throw new OperationException(CommonCode.INVALID_INPUT_PARAMETER, "Invalid input params");
    }

    int actionCount = 0;
    Field[] fields = instance.getClass().getDeclaredFields();
    for (Field field : fields) {
        field.setAccessible(true);
        if (NEED_IGNORE_FIELD.equals(field.getName())) {
            continue;
        }

        try {
            if (null != field.get(instance)) {
                ++actionCount;
            }
        } catch (Exception e) {
            LOGGER.error("checkActionCount exception for req:" + instance, e);
            throw new OperationException(CommonCode.INVALID_INPUT_PARAMETER, "Invalid input params");
        }
    }

    if (ACTION_COUNT_ONE != actionCount) {
        LOGGER.error("checkActionCount FAILED! the number of action in request:{} is not " + ACTION_COUNT_ONE,
                instance);
        throw new OperationException(CommonCode.INVALID_INPUT_PARAMETER, "Invalid input params");
    }
}

From source file:de.cosmocode.palava.salesforce.sync.NullFieldCollector.java

private static void collect(Set<String> nullFields, Object object) {
    LOG.trace("Collecting null fields on {}", object);
    final Field[] fields = object.getClass().getDeclaredFields();
    for (Field field : fields) {
        if (Modifier.isStatic(field.getModifiers()))
            continue;
        if ("fieldsToNull".equals(field.getName()))
            continue;
        try {//from   w w  w.  j  av a2s. co  m
            final boolean accessible = field.isAccessible();
            field.setAccessible(true);
            final Object value = field.get(object);
            field.setAccessible(accessible);
            if (value == null) {
                continue;
            } else if (value instanceof JAXBElement<?>) {
                final JAXBElement<?> jaxb = JAXBElement.class.cast(value);
                if (jaxb.getValue() == null) {
                    nullFields.add(nameOf(field));
                }
            }
        } catch (IllegalAccessException e) {
            throw new IllegalArgumentException(e);
        }
    }
    LOG.trace("Null fields on {}: {}", object, nullFields);
}