List of usage examples for java.lang.reflect Field setAccessible
@Override @CallerSensitive public void setAccessible(boolean flag)
From source file:org.mongojack.internal.util.JacksonAccessor.java
private static Field findField(Class clazz, String name) { try {//from w w w .j a v a 2s .c om Field field = clazz.getDeclaredField(name); field.setAccessible(true); return field; } catch (NoSuchFieldException e) { throw new RuntimeException(e); } }
From source file:se.berazy.api.examples.App.java
/** * Writes out all public fields.//w w w . j av a2 s . c o m * @param T response */ static <T> void outPutResponse(T response) { String retval = "\nResponse: \n"; Class<?> clazz = response.getClass(); Field[] fields = clazz.getDeclaredFields(); for (Field field : fields) { field.setAccessible(true); if (!field.getName().equalsIgnoreCase("ExtensionData")) { try { retval += String.format("%s: %s\n", field.getName(), field.get(response)); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } } } System.out.println(retval); }
From source file:Main.java
public static ContentValues objectToContentValues(Object object) { if (object == null) { throw new IllegalArgumentException("please check your argument"); }/*from w ww. j a v a 2 s . c o m*/ ContentValues contentValues = new ContentValues(); try { Field[] fields = object.getClass().getDeclaredFields(); for (Field field : fields) { String fieldName = field.getName(); Type type = field.getType(); field.setAccessible(true); if (type.equals(String.class)) { contentValues.put(fieldName, field.get(object).toString()); } else if (type.equals(Integer.class) || type.equals(Integer.TYPE)) { contentValues.put(fieldName, field.getInt(object)); } else if (type.equals(Float.class) || type.equals(Float.TYPE)) { contentValues.put(fieldName, field.getFloat(object)); } else if (type.equals(Long.class) || type.equals(Long.TYPE)) { contentValues.put(fieldName, field.getLong(object)); } else if (type.equals(Double.class) || type.equals(Double.TYPE)) { contentValues.put(fieldName, field.getDouble(object)); } else if (type.equals(Boolean.class) || type.equals(Boolean.TYPE)) { contentValues.put(fieldName, field.getBoolean(object)); } } } catch (IllegalAccessException | IllegalArgumentException e) { e.printStackTrace(); } return contentValues; }
From source file:com.microsoft.rest.Validator.java
/** * Validates a user provided required parameter to be not null. * A {@link ServiceException} is thrown if a property fails the validation. * * @param parameter the parameter to validate * @throws ServiceException failures wrapped in {@link ServiceException} *//*from w w w . j av a 2 s. co m*/ public static void validate(Object parameter) throws ServiceException { // Validation of top level payload is done outside if (parameter == null) { return; } Class parameterType = parameter.getClass(); if (ClassUtils.isPrimitiveOrWrapper(parameterType) || parameterType.isEnum() || ClassUtils.isAssignable(parameterType, LocalDate.class) || ClassUtils.isAssignable(parameterType, DateTime.class) || ClassUtils.isAssignable(parameterType, String.class) || ClassUtils.isAssignable(parameterType, DateTimeRfc1123.class) || ClassUtils.isAssignable(parameterType, Period.class)) { return; } Field[] fields = FieldUtils.getAllFields(parameterType); for (Field field : fields) { field.setAccessible(true); JsonProperty annotation = field.getAnnotation(JsonProperty.class); Object property; try { property = field.get(parameter); } catch (IllegalAccessException e) { throw new ServiceException(e); } if (property == null) { if (annotation != null && annotation.required()) { throw new ServiceException( new IllegalArgumentException(field.getName() + " is required and cannot be null.")); } } else { try { Class propertyType = property.getClass(); if (ClassUtils.isAssignable(propertyType, List.class)) { List<?> items = (List<?>) property; for (Object item : items) { Validator.validate(item); } } else if (ClassUtils.isAssignable(propertyType, Map.class)) { Map<?, ?> entries = (Map<?, ?>) property; for (Map.Entry<?, ?> entry : entries.entrySet()) { Validator.validate(entry.getKey()); Validator.validate(entry.getValue()); } } else if (parameter.getClass().getDeclaringClass() != propertyType) { Validator.validate(property); } } catch (ServiceException ex) { IllegalArgumentException cause = (IllegalArgumentException) (ex.getCause()); if (cause != null) { // Build property chain throw new ServiceException( new IllegalArgumentException(field.getName() + "." + cause.getMessage())); } else { throw ex; } } } } }
From source file:utils.ReflectionService.java
public static JsonNode createJsonNode(Class clazz, int maxDeep) { if (maxDeep <= 0 || JsonNode.class.isAssignableFrom(clazz)) { return null; }//w w w . j av a 2s .c om ObjectMapper objectMapper = new ObjectMapper(); ObjectNode objectNode = objectMapper.createObjectNode(); for (Field field : clazz.getDeclaredFields()) { field.setAccessible(true); String key = field.getName(); try { // is array or collection if (field.getType().isArray() || Collection.class.isAssignableFrom(field.getType())) { ParameterizedType collectionType = (ParameterizedType) field.getGenericType(); Class<?> type = (Class<?>) collectionType.getActualTypeArguments()[0]; ArrayNode arrayNode = objectMapper.createArrayNode(); arrayNode.add(createJsonNode(type, maxDeep - 1)); objectNode.put(key, arrayNode); } else { Class<?> type = field.getType(); if (Modifier.isStatic(field.getModifiers())) { continue; } else if (type.isEnum()) { objectNode.put(key, Enum.class.getName()); } else if (!type.getName().startsWith("java") && !key.startsWith("_")) { objectNode.put(key, createJsonNode(type, maxDeep - 1)); } else { objectNode.put(key, type.getName()); } } } catch (Exception e) { e.printStackTrace(); } } return objectNode; }
From source file:com.github.sumimakito.quickkv.util.DataProcessor.java
public static void printFieldsOfObject(Object object) { System.out.println("[Fields of Object: " + object.getClass().getSimpleName() + "]"); for (Field field : object.getClass().getDeclaredFields()) { field.setAccessible(true); // You might want to set modifier to public first. Object value = null;/*w w w. j a v a 2 s . c o m*/ try { value = field.get(object); if (value != null) { System.out.println("- (" + value.getClass().getSimpleName() + ")[" + field.getName() + "]=[" + value + "]"); } } catch (IllegalAccessException e) { e.printStackTrace(); } } }
From source file:Main.java
public static <C> C cloneObject(C original) { try {// w w w. java 2 s. c o m C clone = (C) original.getClass().newInstance(); for (Field field : getAllFieldsValues(original.getClass())) { field.setAccessible(true); if (field.get(original) == null || Modifier.isFinal(field.getModifiers())) { continue; } if (field.getType().isPrimitive() || field.getType().equals(String.class) || field.getType().getSuperclass().equals(Number.class) || field.getType().equals(Boolean.class)) { field.set(clone, field.get(original)); } else { Object childObj = field.get(original); if (childObj == original) { field.set(clone, clone); } else { field.set(clone, cloneObject(field.get(original))); } } } return clone; } catch (Exception e) { return null; } }
From source file:io.wcm.caravan.commons.httpasyncclient.impl.HttpClientTestUtils.java
private static Object getField(Object object, Class clazz, String fieldName) { Field field; try {/* www .j a v a2s . c o m*/ field = clazz.getDeclaredField(fieldName); field.setAccessible(true); return field.get(object); } catch (NoSuchFieldException ex) { Class superClazz = clazz.getSuperclass(); if (superClazz != null) { return getField(object, superClazz, fieldName); } else { throw new RuntimeException("Unable to get field value for '" + fieldName + "'.", ex); } } catch (SecurityException | IllegalArgumentException | IllegalAccessException ex) { throw new RuntimeException("Unable to get field value for '" + fieldName + "'.", ex); } }
From source file:ReflectionHelper.java
/** * Set the value of the field of the object to the given value. * //from ww w .j ava 2s .c o m * @param original * object to modify * @param field * field to modify * @param value * new value for the given object and field * @throws NoSuchFieldException * @throws IllegalAccessException */ public static void setStaticFinalField(Object original, Field field, Object value) throws NoSuchFieldException, IllegalAccessException { // we mark the field to be public field.setAccessible(true); // next we change the modifier in the Field instance to // not be final anymore, thus tricking reflection into // letting us modify the static final field Field modifiersField = Field.class.getDeclaredField(MODIFIERS_FIELD); modifiersField.setAccessible(true); int modifiers = modifiersField.getInt(field); // blank out the final bit in the modifiers int modifiers &= ~Modifier.FINAL; modifiersField.setInt(field, modifiers); FieldAccessor fa = reflection.newFieldAccessor(field, false); fa.set(original, value); }
From source file:com.dwdesign.tweetings.util.WebViewProxySettings.java
private static Object getDeclaredField(Object obj, String name) throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException { final Field f = obj.getClass().getDeclaredField(name); f.setAccessible(true); return f.get(obj); }