List of usage examples for java.lang.reflect Field isAccessible
@Deprecated(since = "9") public boolean isAccessible()
From source file:ch.flashcard.HibernateDetachUtility.java
private static void nullOutFieldsByFieldAccess(Object object, List<Field> classFields, Map<Integer, Object> checkedObjects, Map<Integer, List<Object>> checkedObjectCollisionMap, int depth, SerializationType serializationType) throws Exception { boolean accessModifierFlag = false; for (Field field : classFields) { accessModifierFlag = false;// ww w. j a v a2 s . c o m if (!field.isAccessible()) { field.setAccessible(true); accessModifierFlag = true; } Object fieldValue = field.get(object); if (fieldValue instanceof HibernateProxy) { Object replacement = null; String assistClassName = fieldValue.getClass().getName(); if (assistClassName.contains("javassist") || assistClassName.contains("EnhancerByCGLIB")) { Class assistClass = fieldValue.getClass(); try { Method m = assistClass.getMethod("writeReplace"); replacement = m.invoke(fieldValue); String assistNameDelimiter = assistClassName.contains("javassist") ? "_$$_" : "$$"; assistClassName = assistClassName.substring(0, assistClassName.indexOf(assistNameDelimiter)); if (replacement != null && !replacement.getClass().getName().contains("hibernate")) { nullOutUninitializedFields(replacement, checkedObjects, checkedObjectCollisionMap, depth + 1, serializationType); field.set(object, replacement); } else { replacement = null; } } catch (Exception e) { LOG.error("Unable to write replace object " + fieldValue.getClass(), e); } } if (replacement == null) { String className = ((HibernateProxy) fieldValue).getHibernateLazyInitializer().getEntityName(); //see if there is a context classloader we should use instead of the current one. ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); Class clazz = contextClassLoader == null ? Class.forName(className) : Class.forName(className, true, contextClassLoader); Class[] constArgs = { Integer.class }; Constructor construct = null; try { construct = clazz.getConstructor(constArgs); replacement = construct.newInstance((Integer) ((HibernateProxy) fieldValue) .getHibernateLazyInitializer().getIdentifier()); field.set(object, replacement); } catch (NoSuchMethodException nsme) { try { Field idField = clazz.getDeclaredField("id"); Constructor ct = clazz.getDeclaredConstructor(); ct.setAccessible(true); replacement = ct.newInstance(); if (!idField.isAccessible()) { idField.setAccessible(true); } idField.set(replacement, (Integer) ((HibernateProxy) fieldValue) .getHibernateLazyInitializer().getIdentifier()); } catch (Exception e) { e.printStackTrace(); LOG.error("No id constructor and unable to set field id for base bean " + className, e); } field.set(object, replacement); } } } else { if (fieldValue instanceof PersistentCollection) { // Replace hibernate specific collection types if (!((PersistentCollection) fieldValue).wasInitialized()) { field.set(object, null); } else { Object replacement = null; boolean needToNullOutFields = true; // needed for BZ 688000 if (fieldValue instanceof Map) { replacement = new HashMap((Map) fieldValue); } else if (fieldValue instanceof List) { replacement = new ArrayList((List) fieldValue); } else if (fieldValue instanceof Set) { ArrayList l = new ArrayList((Set) fieldValue); // cannot recurse Sets, see BZ 688000 nullOutUninitializedFields(l, checkedObjects, checkedObjectCollisionMap, depth + 1, serializationType); replacement = new HashSet(l); // convert it back to a Set since that's the type of the real collection, see BZ 688000 needToNullOutFields = false; } else if (fieldValue instanceof Collection) { replacement = new ArrayList((Collection) fieldValue); } setField(object, field.getName(), replacement); if (needToNullOutFields) { nullOutUninitializedFields(replacement, checkedObjects, checkedObjectCollisionMap, depth + 1, serializationType); } } } else { if (fieldValue != null && (fieldValue.getClass().getName().contains("org.rhq") || fieldValue instanceof Collection || fieldValue instanceof Object[] || fieldValue instanceof Map)) nullOutUninitializedFields((fieldValue), checkedObjects, checkedObjectCollisionMap, depth + 1, serializationType); } } if (accessModifierFlag) { field.setAccessible(false); } } }
From source file:org.bremersee.common.exception.ExceptionRegistry.java
/** * Sets a message on the specified throwable. * * @param throwable the throwable// w w w . ja v a 2s.co m * @param message the message */ private static void putMessage(Throwable throwable, String message) { if (throwable == null || StringUtils.isBlank(message)) { return; } Validate.notNull(throwable, "Throwable must not be null."); try { Field messageField = findMessageField(throwable); if (messageField != null) { if (!messageField.isAccessible()) { messageField.setAccessible(true); } messageField.set(throwable, message); } else { LOG.warn("Putting message [" + message + "] to throwable [" + throwable.getClass().getName() // NOSONAR + "] failed: There's no field with name ''detailMessage"); } } catch (RuntimeException re) { LOG.error("Putting message [" + message + "] to throwable [" + throwable.getClass().getName() + "] failed.", re); throw re; } catch (IllegalAccessException iae) { LOG.error("Putting message [" + message + "] to throwable [" + throwable.getClass().getName() + "] failed.", iae); } }
From source file:org.apache.atlas.storm.hook.StormTopologyUtil.java
public static Map<String, String> getFieldValues(Object instance, boolean prependClassName, Set<Object> objectsToSkip) throws IllegalAccessException { if (objectsToSkip == null) { objectsToSkip = new HashSet<>(); }//from ww w . ja v a 2s.c o m Map<String, String> output = new HashMap<>(); try { if (objectsToSkip.add(instance)) { Class clazz = instance.getClass(); for (Class<?> c = clazz; c != null; c = c.getSuperclass()) { Field[] fields = c.getDeclaredFields(); for (Field field : fields) { if (java.lang.reflect.Modifier.isStatic(field.getModifiers())) { continue; } String key; if (prependClassName) { key = String.format("%s.%s", clazz.getSimpleName(), field.getName()); } else { key = field.getName(); } boolean accessible = field.isAccessible(); if (!accessible) { field.setAccessible(true); } Object fieldVal = field.get(instance); if (fieldVal == null) { continue; } else if (fieldVal.getClass().isPrimitive() || isWrapperType(fieldVal.getClass())) { if (toString(fieldVal, false).isEmpty()) continue; output.put(key, toString(fieldVal, false)); } else if (isMapType(fieldVal.getClass())) { //TODO: check if it makes more sense to just stick to json // like structure instead of a flatten output. Map map = (Map) fieldVal; for (Object entry : map.entrySet()) { Object mapKey = ((Map.Entry) entry).getKey(); Object mapVal = ((Map.Entry) entry).getValue(); String keyStr = getString(mapKey, false, objectsToSkip); String valStr = getString(mapVal, false, objectsToSkip); if (StringUtils.isNotEmpty(valStr)) { output.put(String.format("%s.%s", key, keyStr), valStr); } } } else if (isCollectionType(fieldVal.getClass())) { //TODO check if it makes more sense to just stick to // json like structure instead of a flatten output. Collection collection = (Collection) fieldVal; if (collection.size() == 0) continue; String outStr = ""; for (Object o : collection) { outStr += getString(o, false, objectsToSkip) + ","; } if (outStr.length() > 0) { outStr = outStr.substring(0, outStr.length() - 1); } output.put(key, String.format("%s", outStr)); } else { Map<String, String> nestedFieldValues = getFieldValues(fieldVal, false, objectsToSkip); for (Map.Entry<String, String> entry : nestedFieldValues.entrySet()) { output.put(String.format("%s.%s", key, entry.getKey()), entry.getValue()); } } if (!accessible) { field.setAccessible(false); } } } } } catch (Exception e) { LOG.warn("Exception while constructing topology", e); } return output; }
From source file:com.helpinput.utils.Utils.java
public static Field accessible(Field theField) { if (theField != null) { if (!theField.isAccessible()) theField.setAccessible(true); }//w w w . ja va2 s. co m return theField; }
From source file:com.zlfun.framework.excel.ExcelUtils.java
private static void set(Object obj, Field field, String value) { if (value == null) { return;/*from w w w .j a va2s .com*/ } try { if (!field.isAccessible()) { field.setAccessible(true); } Object val = value; if (field.getType() == int.class) { try { val = Integer.parseInt(value); } catch (Exception ex) { val = -1; } } else if (field.getType() == long.class) { try { val = Long.parseLong(value); } catch (Exception ex) { val = -1l; } } else if (field.getType() == double.class) { val = Double.parseDouble(value); } else if (field.getType() == byte.class) { val = Byte.parseByte(value); } else if (field.getType() == boolean.class) { val = Boolean.parseBoolean(value); } field.set(obj, val); } catch (Exception e) { } }
From source file:br.com.lucasisrael.regra.reflections.TratamentoReflections.java
/** * Make the given field accessible, explicitly setting it accessible if * necessary. The {@code setAccessible(true)} method is only called * when actually necessary, to avoid unnecessary conflicts with a JVM * SecurityManager (if active).//from w ww . j ava2s. c o m * @param field the field to make accessible * @see java.lang.reflect.Field#setAccessible */ public static void makeAccessible(Field field) { if ((!Modifier.isPublic(field.getModifiers()) || !Modifier.isPublic(field.getDeclaringClass().getModifiers()) || Modifier.isFinal(field.getModifiers())) && !field.isAccessible()) { field.setAccessible(true); } }
From source file:tech.sirwellington.alchemy.generator.ObjectGenerators.java
private static void injectField(Object pojo, Field field, Map<Class<?>, AlchemyGenerator<?>> generatorMappings) throws IllegalArgumentException, IllegalAccessException { Class<?> typeOfField = field.getType(); typeOfField = ClassUtils.primitiveToWrapper(typeOfField); AlchemyGenerator<?> generator = determineGeneratorFor(typeOfField, field, generatorMappings); if (generator == null) { LOG.warn("Could not find a suitable AlchemyGenerator for field {} with type {}", field, typeOfField); return;/* w w w. ja v a2s . co m*/ } Object value = generator.get(); boolean originalAccessibility = field.isAccessible(); try { field.setAccessible(true); field.set(pojo, value); } finally { field.setAccessible(originalAccessibility); } }
From source file:com.puppycrawl.tools.checkstyle.internal.XdocsPagesTest.java
private static void validateErrorSection(String fileName, String sectionName, Node subSection, Object instance) throws Exception { final Class<?> clss = instance.getClass(); final Set<Field> fields = CheckUtil.getCheckMessages(clss); final Set<String> list = new TreeSet<>(); for (Field field : fields) { // below is required for package/private classes if (!field.isAccessible()) { field.setAccessible(true);// w w w. j a va 2 s . c o m } list.add(field.get(null).toString()); } final StringBuilder expectedText = new StringBuilder(); for (String s : list) { expectedText.append(s); expectedText.append("\n"); } if (expectedText.length() > 0) { expectedText.append("All messages can be customized if the default message doesn't " + "suit you.\nPlease see the documentation to learn how to."); } if (subSection == null) { Assert.assertEquals(fileName + " section '" + sectionName + "' should have the expected error keys", "", expectedText.toString()); } else { Assert.assertEquals(fileName + " section '" + sectionName + "' should have the expected error keys", expectedText.toString().trim(), subSection.getTextContent().replaceAll("\n\\s+", "\n").trim()); for (Node node : XmlUtil.findChildElementsByTag(subSection, "a")) { final String url = node.getAttributes().getNamedItem("href").getTextContent(); final String linkText = node.getTextContent().trim(); final String expectedUrl; if ("see the documentation".equals(linkText)) { expectedUrl = "config.html#Custom_messages"; } else { expectedUrl = "https://github.com/search?q=" + "path%3Asrc%2Fmain%2Fresources%2F" + clss.getPackage().getName().replace(".", "%2F") + "+filename%3Amessages*.properties+repo%3Acheckstyle%2Fcheckstyle+%22" + linkText + "%22"; } Assert.assertEquals( fileName + " section '" + sectionName + "' should have matching url for '" + linkText + "'", expectedUrl, url); } } }
From source file:org.initialize4j.service.modify.ConverterModifier.java
private void modifyFieldWithChangedValue(Object bean, String fieldName, Object convertedValue) throws Exception { Field field = bean.getClass().getDeclaredField(fieldName); boolean accessible = field.isAccessible(); field.setAccessible(true);/*from w w w.j a va 2s. c o m*/ field.set(bean, convertedValue); field.setAccessible(accessible); }
From source file:com.hp.autonomy.frontend.configuration.AbstractConfig.java
@Override @JsonIgnore//from w ww . j ava 2 s . com public Map<String, ConfigurationComponent> getValidationMap() { // Use getDeclaredFields as the fields will probably be private final Field[] fields = this.getClass().getDeclaredFields(); final Map<String, ConfigurationComponent> result = new HashMap<>(); for (final Field field : fields) { final boolean oldValue = field.isAccessible(); try { field.setAccessible(true); final Object o = field.get(this); // if o is null this is false if (o instanceof ConfigurationComponent) { result.put(field.getName(), (ConfigurationComponent) o); } } catch (IllegalAccessException e) { throw new AssertionError("Your JVM does not allow you to run this code.", e); } finally { field.setAccessible(oldValue); } } return result; }