List of usage examples for java.lang.reflect Field isAccessible
@Deprecated(since = "9") public boolean isAccessible()
From source file:org.querybyexample.jpa.JpaUtil.java
public static Object getValueFromField(Field field, Object object) { boolean accessible = field.isAccessible(); try {//from w w w . j a v a 2 s. co m return ReflectionUtils.getField(field, object); } finally { field.setAccessible(accessible); } }
From source file:Main.java
public static Object getFieldValue(Object object, String fieldName) { try {//w w w .ja v a 2 s .c om final Field field = getField(object.getClass(), fieldName); if (field == null) { throw new IllegalArgumentException("No field '" + fieldName + "' found in " + object.getClass().getName() + " or its super classes"); } if (!field.isAccessible()) { field.setAccessible(true); } return field.get(object); } catch (final Exception e) { throw new RuntimeException(e); } }
From source file:org.overlord.sramp.atom.archive.expand.ZipToSrampArchiveTest.java
/** * Gets the JAR working directory.// ww w. j a v a2s . co m * @param j2sramp * @return the private JAR working directory * @throws Exception */ public static File getJarWorkDir(ZipToSrampArchive j2sramp) throws Exception { Field field = getJarWorkDirField(j2sramp); boolean oldAccessible = field.isAccessible(); field.setAccessible(true); File workDir = (File) field.get(j2sramp); field.setAccessible(oldAccessible); return workDir; }
From source file:bdi4jade.util.ReflectionUtils.java
/** * Sets plan body fields annotated with {@link bdi4jade.annotation.Belief}. * //from w w w . jav a 2 s . c o m * @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: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); }/* w ww . ja v a2 s . c o m*/ }
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 ww.jav a2 s . com*/ 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); }
From source file:cn.wanghaomiao.seimi.core.SeimiBeanResolver.java
public static <T> T parse(Class<T> target, String text) throws Exception { T bean = target.newInstance();// w w w.j a v a2s .com final List<Field> props = new LinkedList<>(); ReflectionUtils.doWithFields(target, new ReflectionUtils.FieldCallback() { @Override public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException { props.add(field); } }); JXDocument jxDocument = new JXDocument(text); for (Field f : props) { Xpath xpathInfo = f.getAnnotation(Xpath.class); if (xpathInfo != null) { String xpath = xpathInfo.value(); List<Object> res = jxDocument.sel(xpath); boolean accessFlag = f.isAccessible(); f.setAccessible(true); f.set(bean, defaultCastToTargetValue(target, f, res)); f.setAccessible(accessFlag); } } return bean; }
From source file:com.hurence.logisland.util.string.StringUtilsTest.java
/** * Sets an environment variable FOR THE CURRENT RUN OF THE JVM * Does not actually modify the system's environment variables, * but rather only the copy of the variables that java has taken, * and hence should only be used for testing purposes! * @param key The Name of the variable to set * @param value The value of the variable to set *///from ww w. ja v a2s .c om @SuppressWarnings("unchecked") public static <K, V> void setEnv(final String key, final String value) throws InvocationTargetException { try { /// we obtain the actual environment final Class<?> processEnvironmentClass = Class.forName("java.lang.ProcessEnvironment"); final Field theEnvironmentField = processEnvironmentClass.getDeclaredField("theEnvironment"); final boolean environmentAccessibility = theEnvironmentField.isAccessible(); theEnvironmentField.setAccessible(true); final Map<K, V> env = (Map<K, V>) theEnvironmentField.get(null); if (SystemUtils.IS_OS_WINDOWS) { // This is all that is needed on windows running java jdk 1.8.0_92 if (value == null) { env.remove(key); } else { env.put((K) key, (V) value); } } else { // This is triggered to work on openjdk 1.8.0_91 // The ProcessEnvironment$Variable is the key of the map final Class<K> variableClass = (Class<K>) Class.forName("java.lang.ProcessEnvironment$Variable"); final Method convertToVariable = variableClass.getMethod("valueOf", String.class); final boolean conversionVariableAccessibility = convertToVariable.isAccessible(); convertToVariable.setAccessible(true); // The ProcessEnvironment$Value is the value fo the map final Class<V> valueClass = (Class<V>) Class.forName("java.lang.ProcessEnvironment$Value"); final Method convertToValue = valueClass.getMethod("valueOf", String.class); final boolean conversionValueAccessibility = convertToValue.isAccessible(); convertToValue.setAccessible(true); if (value == null) { env.remove(convertToVariable.invoke(null, key)); } else { // we place the new value inside the map after conversion so as to // avoid class cast exceptions when rerunning this code env.put((K) convertToVariable.invoke(null, key), (V) convertToValue.invoke(null, value)); // reset accessibility to what they were convertToValue.setAccessible(conversionValueAccessibility); convertToVariable.setAccessible(conversionVariableAccessibility); } } // reset environment accessibility theEnvironmentField.setAccessible(environmentAccessibility); // we apply the same to the case insensitive environment final Field theCaseInsensitiveEnvironmentField = processEnvironmentClass .getDeclaredField("theCaseInsensitiveEnvironment"); final boolean insensitiveAccessibility = theCaseInsensitiveEnvironmentField.isAccessible(); theCaseInsensitiveEnvironmentField.setAccessible(true); // Not entirely sure if this needs to be casted to ProcessEnvironment$Variable and $Value as well final Map<String, String> cienv = (Map<String, String>) theCaseInsensitiveEnvironmentField.get(null); if (value == null) { // remove if null cienv.remove(key); } else { cienv.put(key, value); } theCaseInsensitiveEnvironmentField.setAccessible(insensitiveAccessibility); } catch (final ClassNotFoundException | NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { throw new IllegalStateException("Failed setting environment variable <" + key + "> to <" + value + ">", e); } catch (final NoSuchFieldException e) { // we could not find theEnvironment final Map<String, String> env = System.getenv(); Stream.of(Collections.class.getDeclaredClasses()) // obtain the declared classes of type $UnmodifiableMap .filter(c1 -> "java.util.Collections$UnmodifiableMap".equals(c1.getName())).map(c1 -> { try { return c1.getDeclaredField("m"); } catch (final NoSuchFieldException e1) { throw new IllegalStateException("Failed setting environment variable <" + key + "> to <" + value + "> when locating in-class memory map of environment", e1); } }).forEach(field -> { try { final boolean fieldAccessibility = field.isAccessible(); field.setAccessible(true); // we obtain the environment final Map<String, String> map = (Map<String, String>) field.get(env); if (value == null) { // remove if null map.remove(key); } else { map.put(key, value); } // reset accessibility field.setAccessible(fieldAccessibility); } catch (final ConcurrentModificationException e1) { // This may happen if we keep backups of the environment before calling this method // as the map that we kept as a backup may be picked up inside this block. // So we simply skip this attempt and continue adjusting the other maps // To avoid this one should always keep individual keys/value backups not the entire map System.out.println("Attempted to modify source map: " + field.getDeclaringClass() + "#" + field.getName() + e1); } catch (final IllegalAccessException e1) { throw new IllegalStateException("Failed setting environment variable <" + key + "> to <" + value + ">. Unable to access field!", e1); } }); } System.out.println( "Set environment variable <" + key + "> to <" + value + ">. Sanity Check: " + System.getenv(key)); }
From source file:misc.TestUtils.java
public static List<Pair<String, Object>> getEntityFields(Object o) { List<Pair<String, Object>> ret = new ArrayList<Pair<String, Object>>(); for (Class<?> clazz = o.getClass(); clazz != Object.class; clazz = clazz.getSuperclass()) { for (Field field : clazz.getDeclaredFields()) { //ignore some weird fields with unique values if (field.getName().contains("$")) continue; boolean accessible = field.isAccessible(); try { field.setAccessible(true); Object val = field.get(o); ret.add(new Pair<String, Object>(field.getName(), val)); // System.out.println(field.getName()+"="+val); } catch (IllegalArgumentException e) { e.printStackTrace();//www. j ava 2 s . c o m } catch (IllegalAccessException e) { e.printStackTrace(); } catch (SecurityException e) { e.printStackTrace(); } finally { field.setAccessible(accessible); } } } return ret; }
From source file:com.palantir.ptoss.util.Reflections.java
/** * Given an {@link Object} and a {@link Field} of a known {@link Class} type, get the field. * This will return the value of the field regardless of visibility modifiers (i.e., it will * return the value of private fields.)//from w w w. j ava 2s.c o m */ public static <T> T getFieldObject(Object object, Field field, Class<T> klass) { try { boolean accessible = field.isAccessible(); field.setAccessible(true); Object fieldObject = field.get(object); field.setAccessible(accessible); return klass.cast(fieldObject); } catch (IllegalAccessException e) { // shouldn't happen since we set accessibility above. return null; } }