@Test public void shouldEnableAndThenDisableAccessibility() throws Exception { // given Field privateField = SomeObject.class.getDeclaredField("privateField"); assertFalse(privateField.isAccessible()); // when tool.copyToMock(from, to); // then privateField = SomeObject.class.getDeclaredField("privateField"); assertFalse(privateField.isAccessible()); }
public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) { Object obj = context.currentObject(); if (obj == null) { try { obj = context.getRequiredType().newInstance(); } catch (Exception e) { throw new ObjectAccessException( "Cannot construct " + context.getRequiredType().getName(), e); } } Iterator attNames = reader.getAttributeNames(); while (attNames.hasNext()) { String attName = (String) attNames.next(); if (attName.equals(textName)) { continue; } try { Field field = obj.getClass().getDeclaredField(mapper.realMember(obj.getClass(), attName)); if (!field.isAccessible()) { field.setAccessible(true); } String v = reader.getAttribute(attName); if (null == v || "".equals(v)) { continue; } Class fieldType = field.getType(); Constructor strnum = fieldType.getDeclaredConstructor(String.class); field.set(obj, strnum.newInstance(v)); } catch (Exception e) { e.printStackTrace(); throw new ObjectAccessException("Cannot construct " + obj.getClass(), e); } } String value = reader.getValue(); if (null != value && !"".equals(value)) { try { Field field = obj.getClass().getDeclaredField(mapper.realMember(obj.getClass(), textName)); if (!field.isAccessible()) { field.setAccessible(true); } field.set(obj, value); } catch (Exception e) { e.printStackTrace(); throw new ObjectAccessException("Cannot construct " + obj.getClass(), e); } } return obj; }
public static void CombinationValue( Object paramObject1, Object paramObject2, Class<?> paramClass) { if (paramObject1 == null) { throw new IllegalArgumentException("源对象为空无法拷贝!"); } if (paramObject2 == null) { throw new IllegalArgumentException("目标对象为空无法拷贝!"); } if ((paramObject2 instanceof HibernateProxy)) { HibernateProxy localObject1 = (HibernateProxy) paramObject2; paramObject2 = ((HibernateProxy) localObject1).getHibernateLazyInitializer().getImplementation(); } Object localObject1 = getFieldList(paramObject1, paramClass); List localList = getFieldList(paramObject2, paramClass); Iterator localIterator1 = ((List) localObject1).iterator(); while (localIterator1.hasNext()) { Field localField1 = (Field) localIterator1.next(); Iterator localIterator2 = localList.iterator(); while (localIterator2.hasNext()) { Field localField2 = (Field) localIterator2.next(); if ((localField1.getName().equals(localField2.getName())) && (localField1.getType().equals(localField2.getType())) && (!Modifier.isFinal(localField2.getModifiers()))) { if (!localField1.isAccessible()) { localField1.setAccessible(true); } if (!localField2.isAccessible()) { localField2.setAccessible(true); } try { Object localObject2 = localField1.get(paramObject1); if (localObject2 == null) { break; } if ((localObject2 instanceof StandardModel)) { CombinationValue(localObject2, localField2.get(paramObject2)); } else { localField2.set(paramObject2, localObject2); } } catch (IllegalArgumentException localIllegalArgumentException) { localIllegalArgumentException.printStackTrace(); } catch (IllegalAccessException localIllegalAccessException) { localIllegalAccessException.printStackTrace(); } } } } }
/** * The value of field {@code field} of object {@code object}, returned with static type {@code * expectedType}. The value is read, even on private fields. The security settings must allow * this. */ @MethodContract( pre = { @Expression("object != null"), @Expression("field != null"), @Expression("expectedType != null") }, post = @Expression("field.get(object)"), exc = @Throw( type = ClassCastException.class, cond = @Expression("! fieldValue(object, field) instanceof expectedType"))) public static final <_T_> _T_ fieldValue(Object object, Field field, Class<_T_> expectedType) throws ClassCastException { assert preArgumentNotNull(object, "object"); assert preArgumentNotNull(field, "field"); assert preArgumentNotNull(expectedType, "expectedType"); boolean oldAccessible = field.isAccessible(); field.setAccessible(true); _T_ result = null; try { result = expectedType.cast(field.get(object)); // ClassCastException } catch (IllegalArgumentException exc) { unexpectedException(exc); } catch (IllegalAccessException exc) { unexpectedException(exc); } field.setAccessible(oldAccessible); return result; }
/** * Dynamically register a native library path. This relies on a specific implementation detail of * ClassLoader: it's usr_paths property. * * @param path Library path to add * @return {@code true} if the library path could be added successfully */ protected boolean registerNativeLibraryPath(String path) { if (path == null) { throw new NullPointerException(); } path = path.trim(); try { Field f = ClassLoader.class.getDeclaredField("usr_paths"); boolean accessible = f.isAccessible(); f.setAccessible(true); try { String[] paths = (String[]) f.get(null); // Make sure the path isn't already registered for (String p : paths) { if (p.equals(path)) { return true; // Success, it's already there! } } String[] newPaths = new String[paths.length + 1]; System.arraycopy(paths, 0, newPaths, 0, paths.length); newPaths[paths.length] = path; f.set(null, newPaths); // Success! return true; } finally { f.setAccessible(accessible); } } catch (Exception ex) { // Something went wrong, definitely not successful return false; } }
private void addFields(Class<?> clazz) { Field[] fields = clazz.getDeclaredFields(); for (Field field : fields) { if (canAccessPrivateMethods()) { try { field.setAccessible(true); } catch (Exception e) { // Ignored. This is only a final precaution, nothing we can do. } } if (field.isAccessible()) { if (!setMethods.containsKey(field.getName())) { // issue #379 - removed the check for final because JDK 1.5 allows // modification of final fields through reflection (JSR-133). (JGB) // pr #16 - final static can only be set by the classloader int modifiers = field.getModifiers(); if (!(Modifier.isFinal(modifiers) && Modifier.isStatic(modifiers))) { addSetField(field); } } if (!getMethods.containsKey(field.getName())) { addGetField(field); } } } if (clazz.getSuperclass() != null) { addFields(clazz.getSuperclass()); } }
/** * 为对象的一个字段设值。 优先调用对象的 setter,如果没有,直接设置字段的值 * * @param obj 对象 * @param field 字段 * @param value 值。如果为 null,字符和数字字段,都会设成 0 * @throws FailToSetValueException */ public void setValue(Object obj, Field field, Object value) throws FailToSetValueException { if (!field.isAccessible()) field.setAccessible(true); Class<?> ft = field.getType(); // 非 null 值,进行转换 if (null != value) { try { value = Castors.me().castTo(value, field.getType()); } catch (FailToCastObjectException e) { throw makeSetValueException(obj.getClass(), field.getName(), value, e); } } // 如果是原生类型,转换成默认值 else if (ft.isPrimitive()) { if (boolean.class == ft) { value = false; } else if (char.class == ft) { value = (char) 0; } else { value = (byte) 0; } } try { this.getSetter(field).invoke(obj, value); } catch (Exception e1) { try { field.set(obj, value); } catch (Exception e) { throw makeSetValueException(obj.getClass(), field.getName(), value, e); } } }
/** * 设置预编译参数 * * @param ps 预编译 * @param index 序号 * @param t vo模型 * @param f 字段 * @throws IllegalArgumentException * @throws SQLException * @throws IllegalAccessException */ private void setParamter(PreparedStatement ps, int index, T t, Field f) throws IllegalArgumentException, SQLException, IllegalAccessException { if (!f.isAccessible()) { f.setAccessible(true); } if (isBoolean(f)) { ps.setBoolean(index, f.getBoolean(t)); } else if (isInt(f)) { ps.setInt(index, f.getInt(t)); } else if (isLong(f)) { ps.setLong(index, f.getLong(t)); } else if (isString(f)) { ps.setString(index, (String) f.get(t)); } else if (isDate(f)) { Object o = f.get(t); if (o == null) { ps.setDate(index, null); } else { ps.setTimestamp(index, new java.sql.Timestamp(((Date) o).getTime())); } } else if (isByte(f)) { ps.setByte(index, f.getByte(t)); } else if (isChar(f)) { ps.setInt(index, f.getChar(t)); } else if (isDouble(f)) { ps.setDouble(index, f.getDouble(t)); } else if (isFloat(f)) { ps.setFloat(index, f.getFloat(t)); } else { ps.setObject(index, f.get(t)); } }
public Credentials readCredentials(String credentialsPath) throws IOException, IllegalArgumentException, IllegalAccessException { Properties prop = new Properties(); ClassLoader loader = Thread.currentThread().getContextClassLoader(); InputStream stream = loader.getResourceAsStream(credentialsPath); prop.load(stream); Credentials c = new Credentials(); Field[] declaredFields = Credentials.class.getDeclaredFields(); for (int x = 0, xMax = declaredFields.length; x < xMax; x++) { Field field = declaredFields[x]; String value = prop.getProperty(field.getName(), null); if (value != null) { boolean accessible = field.isAccessible(); // If it's a private field we can: get declared getter method and use it, or modify the // accessibility of the field and edit it field.setAccessible(true); field.set(c, value); field.setAccessible(accessible); } } return c; }
private String translateToString(Packet packet, int pos) { String ptr = " "; if (pos == currentIndex) ptr = " \2474"; if (packet == null) return (count + pos) + "null:[]"; String trans = ptr + (count + pos) + "\247r: " + packet.getClass().getSimpleName() + ": ["; int vars = 0; for (Field f : packet.getClass().getDeclaredFields()) { if (!Modifier.isStatic(f.getModifiers())) { if (!f.isAccessible()) f.setAccessible(true); try { Object obj = f.get(packet); String value = "null"; if (obj != null) value = obj.toString(); trans += " f" + vars + "=" + value + ","; } catch (IllegalArgumentException | IllegalAccessException e) { e.printStackTrace(); } } } if (trans.endsWith(",")) { trans = trans.substring(0, trans.length() - 1); } trans += "]"; return trans; }
@SuppressWarnings("unchecked") public static EntityTrackerEntry registerEntityTracker( Entity entity, int trackingRange, int updateFrequency, boolean sendVelocityUpdates) { WorldServer worldServer = getWorld(entity); CustomEntityTrackerEntry tracker = new CustomEntityTrackerEntry(entity, trackingRange, updateFrequency, sendVelocityUpdates); try { Field field = worldServer.tracker.getClass().getDeclaredField("c"); if (!field.isAccessible()) { field.setAccessible(true); } Set<EntityTrackerEntry> list = (Set<EntityTrackerEntry>) field.get(worldServer.tracker); if (worldServer.tracker.trackedEntities.b(entity.getId())) { // if contains entity tracker // go to delete EntityTrackerEntry oldTracker = worldServer.tracker.trackedEntities.d(entity.getId()); list.remove(oldTracker); oldTracker.a(); } list.add(tracker); worldServer.tracker.trackedEntities.a(entity.getId(), tracker); tracker.scanPlayers(worldServer.players); } catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) { e.printStackTrace(); } return tracker; }
public Object getField(Object target, String fieldName, boolean breakAccessibility) throws ReflectorException { try { Class targetClass = target.getClass(); Field field = targetClass.getField(fieldName); boolean accessibilityBroken = false; if (!field.isAccessible() && breakAccessibility) { field.setAccessible(true); accessibilityBroken = true; } Object result = field.get(target); if (accessibilityBroken) { field.setAccessible(false); } return result; } catch (SecurityException e) { throw new ReflectorException(e); } catch (NoSuchFieldException e) { throw new ReflectorException(e); } catch (IllegalAccessException e) { throw new ReflectorException(e); } }
public WorkItemInfo merge(WorkItemInfo workItemInfo) { if (this.pessimisticLocking) { if (em.contains(workItemInfo)) { em.lock(workItemInfo, LockModeType.PESSIMISTIC_FORCE_INCREMENT); } else { // Yes, this is a hack, but for detached entities, it's the only way to lock before merging WorkItemInfo dbWorkItemInfo = em.find( WorkItemInfo.class, workItemInfo.getId(), LockModeType.PESSIMISTIC_FORCE_INCREMENT); for (Field field : WorkItemInfo.class.getDeclaredFields()) { boolean access = field.isAccessible(); field.setAccessible(true); try { field.set(dbWorkItemInfo, field.get(workItemInfo)); } catch (Exception e) { logger.error( "Unable to set field " + field.getName() + " of unmerged WorkItemInfo instance!", e); } field.setAccessible(access); } } } return em.merge(workItemInfo); }
/** Removed fields cache from original code. */ protected static Collection<Field> getFields(Class<?> clazz) { Collection<Field> fields = ReflectUtil.getFields(clazz); Iterator<Field> iterator = fields.iterator(); while (iterator.hasNext()) { Field field = iterator.next(); if (!field.isAnnotationPresent(SpringBean.class)) { iterator.remove(); } else if (!field.isAccessible()) { // If the field isn't public, try to make it accessible try { field.setAccessible(true); } catch (SecurityException se) { throw new StripesRuntimeException( "Field " + clazz.getName() + "." + field.getName() + "is marked " + "with @SpringBean and is not public. An attempt to call " + "setAccessible(true) resulted in a SecurityException. Please " + "either make the field public, annotate a public setter instead " + "or modify your JVM security policy to allow Stripes to " + "setAccessible(true).", se); } } } return fields; }
private static <T> T getFieldInternal(Object instance, Class<?> fieldOwner, String fieldname) { Field target; try { target = fieldOwner.getDeclaredField(fieldname); } catch (NoSuchFieldException e) { throw Exceptions.newIllegalArgumentException("%s has no field named %s", instance, fieldname); } boolean alreadyAccessible = target.isAccessible(); if (!alreadyAccessible) { target.setAccessible(true); } try { @SuppressWarnings("unchecked") // we've already left statically-typed land, // so we may as well make it convenient for callers T value = (T) target.get(instance); return value; } catch (IllegalAccessException e) { throw Throwables.propagate(e); } finally { if (!alreadyAccessible) { target.setAccessible(false); } } }
public static void setValue(Field field, Object target, Object value) { if (target == null) { throw new IllegalArgumentException("Parameter 'target' can't be null"); } if (field == null) { throw new IllegalArgumentException("Parameter 'field' can't be null"); } boolean accessible = field.isAccessible(); if (!accessible) { field.setAccessible(true); } try { field.set(target, value); } catch (Exception ex) { throw new GrapheneTestEnricherException( "During enriching of " + NEW_LINE + target.getClass() + NEW_LINE + " the field " + NEW_LINE + field + " was not able to be set! Check the cause!", ex); } if (!accessible) { field.setAccessible(false); } }
@Override public void enrich(final SearchContext searchContext, Object target) { Collection<Field> fields = ReflectionHelper.getFieldsWithAnnotation(target.getClass(), JavaScript.class); for (Field field : fields) { GrapheneContext grapheneContext = searchContext == null ? null : ((GrapheneProxyInstance) searchContext).getGrapheneContext(); if (grapheneContext == null) { grapheneContext = GrapheneContext.getContextFor(ReflectionHelper.getQualifier(field.getAnnotations())); } if (!field.isAccessible()) { field.setAccessible(true); } try { field.set(target, JSInterfaceFactory.create(grapheneContext, field.getType())); } catch (Exception e) { throw new IllegalStateException( "Can't inject value to the field '" + field.getName() + "' declared in class '" + field.getDeclaringClass().getName() + "'", e); } } }
@Before public void setup() throws Throwable { // Instantiating ScmSyncConfigurationPlugin instance ScmSyncConfigurationPlugin scmSyncConfigPluginInstance = new ScmSyncConfigurationPlugin(); // Mocking PluginWrapper attached to current ScmSyncConfigurationPlugin instance PluginWrapper pluginWrapper = PowerMockito.mock(PluginWrapper.class); when(pluginWrapper.getShortName()).thenReturn("scm-sync-configuration"); // Setting field on current plugin instance Field wrapperField = Plugin.class.getDeclaredField("wrapper"); boolean wrapperFieldAccessibility = wrapperField.isAccessible(); wrapperField.setAccessible(true); wrapperField.set(scmSyncConfigPluginInstance, pluginWrapper); wrapperField.setAccessible(wrapperFieldAccessibility); // Mocking Hudson root directory currentTestDirectory = createTmpDirectory("SCMSyncConfigTestsRoot"); currentHudsonRootDirectory = new File(currentTestDirectory.getAbsolutePath() + "/hudsonRootDir/"); if (!(currentHudsonRootDirectory.mkdir())) { throw new IOException( "Could not create hudson root directory: " + currentHudsonRootDirectory.getAbsolutePath()); } FileUtils.copyDirectoryStructure( new ClassPathResource(getHudsonRootBaseTemplate()).getFile(), currentHudsonRootDirectory); // EnvVars env = Computer.currentComputer().getEnvironment(); // env.put("HUDSON_HOME", tmpHudsonRoot.getPath() ); // Creating local SVN repository... curentLocalSvnRepository = new File(currentTestDirectory.getAbsolutePath() + "/svnLocalRepo/"); if (!(curentLocalSvnRepository.mkdir())) { throw new IOException( "Could not create SVN local repo directory: " + curentLocalSvnRepository.getAbsolutePath()); } FileUtils.copyDirectoryStructure( new ClassPathResource("svnEmptyRepository").getFile(), curentLocalSvnRepository); // Mocking user User mockedUser = Mockito.mock(User.class); when(mockedUser.getId()).thenReturn("fcamblor"); // Mocking Hudson singleton instance ... // Warning : this line will only work on Objenesis supported VMs : // http://code.google.com/p/objenesis/wiki/ListOfCurrentlySupportedVMs Hudson hudsonMockedInstance = spy((Hudson) new ObjenesisStd().getInstantiatorOf(Hudson.class).newInstance()); PowerMockito.doReturn(currentHudsonRootDirectory).when(hudsonMockedInstance).getRootDir(); PowerMockito.doReturn(mockedUser).when(hudsonMockedInstance).getMe(); PowerMockito.doReturn(scmSyncConfigPluginInstance) .when(hudsonMockedInstance) .getPlugin(ScmSyncConfigurationPlugin.class); PowerMockito.mockStatic(Hudson.class); PowerMockito.doReturn(hudsonMockedInstance).when(Hudson.class); Hudson.getInstance(); // when(Hudson.getInstance()).thenReturn(hudsonMockedInstance); }
/** * 把查询结果填充到vo中 * * @param rs 查询结果,由调用负责游标 * @param t vo * @throws IllegalArgumentException * @throws IllegalAccessException * @throws SQLException */ private void fillVO(ResultSet rs, T t) throws IllegalArgumentException, IllegalAccessException, SQLException { for (Field f : listTableFields(t.getClass())) { String name = findFieldName(f); Object object = rs.getObject(name); if (object != null) { if (!f.isAccessible()) { f.setAccessible(true); } if (isBoolean(f)) { f.setBoolean(t, rs.getBoolean(name)); } else if (isInt(f)) { f.setInt(t, rs.getInt(name)); } else if (isLong(f)) { f.setLong(t, rs.getLong(name)); } else if (isString(f)) { f.set(t, rs.getString(name)); } else if (isDate(f)) { f.set(t, rs.getTimestamp(name)); } else if (isByte(f)) { f.setByte(t, rs.getByte(name)); } else if (isChar(f)) { f.setChar(t, rs.getString(name).charAt(0)); } else if (isDouble(f)) { f.setDouble(t, rs.getDouble(name)); } else if (isFloat(f)) { f.setFloat(t, rs.getFloat(name)); } else { f.set(t, object); } } } }
private Field[] getAccessibleFields(boolean includeProtected, boolean includePrivate) { if (includePrivate || includeProtected) { try { List<Field> fieldsList = new ArrayList<Field>(); Class<?> currentClass = cl; while (currentClass != null) { // get all declared fields in this class, make them // accessible, and save Field[] declared = currentClass.getDeclaredFields(); for (Field field : declared) { int mod = field.getModifiers(); if (includePrivate || isPublic(mod) || isProtected(mod)) { if (!field.isAccessible()) field.setAccessible(true); fieldsList.add(field); } } // walk up superclass chain. no need to deal specially with // interfaces, since they can't have fields currentClass = currentClass.getSuperclass(); } return fieldsList.toArray(new Field[fieldsList.size()]); } catch (SecurityException e) { // fall through to !includePrivate case } } return cl.getFields(); }
// obj: "object with properties" to write private void writeObject(Object obj) throws NoSuchMethodException, InstantiationException, InvocationTargetException, IllegalAccessException, SecurityException { // begin bean encoding: this.driver.startElement(DTD.ELEMENT_OBJECT); Class cls = obj.getClass(); final String mappedName = this.context.aliasFor(cls); this.driver.setAttribute( DTD.ATTRIBUTE_CLASS, (mappedName != null ? mappedName : cls.getName())); // encode properties: while (cls != Object.class) { // process inheritance: for (Field f : cls.getDeclaredFields()) { // process composition: if (Modifier.isStatic(f.getModifiers()) || !ReflectionUtil.hasClassFieldProperty(cls, f) || this.context.excluded(f)) { continue; // skip static or non-property or excluded field. } // get property field: if (!f.isAccessible()) { f.setAccessible(true); } // write property value: final String aliasedFieldName = this.context.aliasFor(f, f.getName()); this.driver.startElement(aliasedFieldName); this.write0(f.get(obj)); this.driver.endElement(); } cls = cls.getSuperclass(); } // end bean encoding: this.driver.endElement(); }
private void applyElement() { Field[] fields = getClass().getDeclaredFields(); for (Field field : fields) { StructMapping structMapping = field.getAnnotation(StructMapping.class); if (structMapping != null) { int length = structMapping.length(); int offset = structMapping.offset(); if (offset == -1) { throw new IllegalStateException( "StructMapping in " + getClass() + " named " + field.getName() + " must declare the offset."); } if (length == -1) { length = SizeOf.INT; } StructMember structVar = new StructMember(structAddress, offset, length); if (!field.isAccessible()) { field.setAccessible(true); } try { field.set(this, structVar); } catch (IllegalAccessException e) { throw new RuntimeException(e.getMessage()); } } } }
private ObjectMap<String, FieldMetadata> cacheFields(Class type) { ArrayList<Field> allFields = new ArrayList(); Class nextClass = type; while (nextClass != Object.class) { Collections.addAll(allFields, nextClass.getDeclaredFields()); nextClass = nextClass.getSuperclass(); } ObjectMap<String, FieldMetadata> nameToField = new ObjectMap(); for (int i = 0, n = allFields.size(); i < n; i++) { Field field = allFields.get(i); int modifiers = field.getModifiers(); if (Modifier.isTransient(modifiers)) continue; if (Modifier.isStatic(modifiers)) continue; if (field.isSynthetic()) continue; if (!field.isAccessible()) { try { field.setAccessible(true); } catch (AccessControlException ex) { continue; } } nameToField.put(field.getName(), new FieldMetadata(field)); } typeToFields.put(type, nameToField); return nameToField; }
public AbstractJaxbObject(T realObject, Class<?> objectInterface) { this(objectInterface); for (Method getIsMethod : objectInterface.getDeclaredMethods()) { String methodName = getIsMethod.getName(); String fieldName; if (methodName.startsWith("get")) { fieldName = methodName.substring(3); } else if (methodName.startsWith("is")) { fieldName = methodName.substring(2); } else { continue; } // getField -> field (lowercase f) fieldName = fieldName.substring(0, 1).toLowerCase() + fieldName.substring(1); try { Field field = this.getClass().getDeclaredField(fieldName); boolean origAccessStatus = field.isAccessible(); field.setAccessible(true); Object setObject = getIsMethod.invoke(realObject, new Object[0]); field.set(this, setObject); field.setAccessible(origAccessStatus); } catch (Exception e) { throw new RuntimeException( "Unable to initialize " + fieldName + " when creating " + this.getClass().getSimpleName() + ".", e); } } }
public static Map<String, String> objectToMap(Object object, String... ignore) { Map<String, String> tempMap = new LinkedHashMap<String, String>(); for (Field f : object.getClass().getDeclaredFields()) { if (!f.isAccessible()) { f.setAccessible(true); } boolean ig = false; if (ignore != null && ignore.length > 0) { for (String i : ignore) { if (i.equals(f.getName())) { ig = true; break; } } } if (ig) { continue; } else { Object o = null; try { o = f.get(object); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } if (o != null) { tempMap.put(f.getName(), o.toString()); } } } return tempMap; }
public static Serializable getIdentifier(final Object obj) { if (obj instanceof BaseDO<?>) { return getIdentifier((BaseDO<?>) obj); } for (final Field field : obj.getClass().getDeclaredFields()) { if (field.isAnnotationPresent(Id.class) == true && field.isAnnotationPresent(GeneratedValue.class) == true) { final boolean isAccessible = field.isAccessible(); try { field.setAccessible(true); final Object idObject = field.get(obj); field.setAccessible(isAccessible); if (idObject != null && Serializable.class.isAssignableFrom(idObject.getClass()) == true) { return (Serializable) idObject; } } catch (final IllegalArgumentException e) { e.printStackTrace(); } catch (final IllegalAccessException e) { e.printStackTrace(); } } } return null; }
public Field getField() { // To support private variables we simply make the field accessible. if (!field.isAccessible()) { field.setAccessible(true); } return field; }
public static <T> T collapseStructure(T object) { if (hasOnlyNullFields(object)) { return null; } List<Field> fields = getAllFields(object.getClass()); try { for (Field field : fields) { if (!field.isAccessible()) { field.setAccessible(true); } if (field.get(object) != null) { if (field.getType().getName().contains("java.util.List")) { @SuppressWarnings("unchecked") List<Object> list = (List<Object>) field.get(object); List<Object> newList = new ArrayList<Object>(list.size()); boolean isNull = true; for (int i = 0; i < list.size(); i++) { Object o = collapseStructure(list.get(i)); if (o != null) { isNull = false; newList.add(o); } } field.set(object, isNull ? null : newList); continue; } else if (field.getType().getName().contains("java.lang.String")) { if ("".equals(((String) field.get(object)).trim())) { field.set(object, null); } continue; } else if (field.getType().getName().contains("CodeOrText") || field.getType().getName().contains("NameTypeAttribute") || field.getType().getName().contains("PlaceAuthority") || field.getType().getName().contains("Yes")) { Field auxField = field.getType().getDeclaredField("value"); auxField.setAccessible(true); String s = (String) auxField.get(field.get(object)); if ("".equals(s)) { field.set(object, null); } continue; } else { collapseStructure(field.get(object)); } } } } catch (IllegalArgumentException e) { LOGGER.error("Unable to inspect the structure via reflection", e); } catch (IllegalAccessException e) { LOGGER.error("Unable to inspect the structure via reflection", e); } catch (SecurityException e) { LOGGER.error("Unable to inspect the structure via reflection", e); } catch (NoSuchFieldException e) { LOGGER.error("Unable to inspect the structure via reflection", e); } if (hasOnlyNullFields(object)) { return null; } return object; }
protected Serializable fieldValue(final Object obj, final AnnotatedElement annotatedElement) { if (annotatedElement instanceof Field) { // a field final Field f = (Field) annotatedElement; if (!f.isAccessible()) { f.setAccessible(true); } try { return (Serializable) f.get(obj); } catch (final IllegalArgumentException e) { logger.warn("获取" + obj.getClass().getName() + "的id字段" + f.getName() + "的值失败。", e); } catch (final IllegalAccessException e) { logger.warn("获取" + obj.getClass().getName() + "的id字段" + f.getName() + "的值失败。", e); } catch (final ClassCastException e) { logger.warn(obj.getClass().getName() + "的id字段" + f.getName() + "不可序列化。", e); } } else { // a method final Method m = (Method) annotatedElement; if (!m.isAccessible()) { m.setAccessible(true); } try { return (Serializable) ReflectionUtils.invokeMethod(m, obj); } catch (final ClassCastException e) { logger.warn(obj.getClass().getName() + "的id字段" + m.getName() + "不可序列化。", e); } } return null; }
@Override public TypedValue read(EvaluationContext context, Object target, String name) throws AccessException { if (this.member instanceof Method) { Method method = (Method) this.member; try { if (this.needsToBeMadeAccessible && !method.isAccessible()) { method.setAccessible(true); } Object value = method.invoke(target); return new TypedValue(value, this.typeDescriptor.narrow(value)); } catch (Exception ex) { throw new AccessException( "Unable to access property '" + name + "' through getter method", ex); } } else { Field field = (Field) this.member; try { if (this.needsToBeMadeAccessible && !field.isAccessible()) { field.setAccessible(true); } Object value = field.get(target); return new TypedValue(value, this.typeDescriptor.narrow(value)); } catch (Exception ex) { throw new AccessException("Unable to access field '" + name + "'", ex); } } }