List of usage examples for java.lang.reflect Field setInt
@CallerSensitive @ForceInline public void setInt(Object obj, int i) throws IllegalArgumentException, IllegalAccessException
From source file:com.browseengine.bobo.serialize.JSONSerializer.java
private static void loadObject(Object retObj, Field f, JSONObject jsonObj) throws JSONSerializationException { String key = f.getName();//from ww w. j av a 2 s .co m Class type = f.getType(); try { if (type.isPrimitive()) { if (type == Integer.TYPE) { f.setInt(retObj, jsonObj.getInt(key)); } else if (type == Long.TYPE) { f.setLong(retObj, jsonObj.getInt(key)); } else if (type == Short.TYPE) { f.setShort(retObj, (short) jsonObj.getInt(key)); } else if (type == Boolean.TYPE) { f.setBoolean(retObj, jsonObj.getBoolean(key)); } else if (type == Double.TYPE) { f.setDouble(retObj, jsonObj.getDouble(key)); } else if (type == Float.TYPE) { f.setFloat(retObj, (float) jsonObj.getDouble(key)); } else if (type == Character.TYPE) { char ch = jsonObj.getString(key).charAt(0); f.setChar(retObj, ch); } else if (type == Byte.TYPE) { f.setByte(retObj, (byte) jsonObj.getInt(key)); } else { throw new JSONSerializationException("Unknown primitive: " + type); } } else if (type == String.class) { f.set(retObj, jsonObj.getString(key)); } else if (JSONSerializable.class.isAssignableFrom(type)) { JSONObject jObj = jsonObj.getJSONObject(key); JSONSerializable serObj = deSerialize(type, jObj); f.set(retObj, serObj); } } catch (Exception e) { throw new JSONSerializationException(e.getMessage(), e); } }
From source file:org.sonar.plugins.openedge.foundation.OpenEdgeComponents.java
private static void configureField(Object check, Field field, String value) { try {//from w w w. j ava2 s.c om field.setAccessible(true); if (field.getType().equals(String.class)) { field.set(check, value); } else if (int.class == field.getType()) { field.setInt(check, Integer.parseInt(value)); } else if (short.class == field.getType()) { field.setShort(check, Short.parseShort(value)); } else if (long.class == field.getType()) { field.setLong(check, Long.parseLong(value)); } else if (double.class == field.getType()) { field.setDouble(check, Double.parseDouble(value)); } else if (boolean.class == field.getType()) { field.setBoolean(check, Boolean.parseBoolean(value)); } else if (byte.class == field.getType()) { field.setByte(check, Byte.parseByte(value)); } else if (Integer.class == field.getType()) { field.set(check, new Integer(Integer.parseInt(value))); } else if (Long.class == field.getType()) { field.set(check, new Long(Long.parseLong(value))); } else if (Double.class == field.getType()) { field.set(check, new Double(Double.parseDouble(value))); } else if (Boolean.class == field.getType()) { field.set(check, Boolean.valueOf(Boolean.parseBoolean(value))); } else { throw MessageException .of("The type of the field " + field + " is not supported: " + field.getType()); } } catch (IllegalAccessException e) { throw MessageException.of( "Can not set the value of the field " + field + " in the class: " + check.getClass().getName(), e); } }
From source file:org.openmrs.module.distrotools.test.TestUtils.java
/** * Modifies a constant in a constants class. If the constant is final and not based on a runtime expression, then * it's value will have been inlined by the compiler and this method will have no effect. * @param constantsClass the class of constants * @param fieldName the field name of the constant * @param newValue the new value for the constant * @throws Exception if field not found or couldn't be modified *//*from ww w . ja va 2s . co m*/ public static void modifyConstant(Class<?> constantsClass, String fieldName, Object newValue) throws Exception { Field field = constantsClass.getDeclaredField(fieldName); field.setAccessible(true); int existingModifiers = field.getModifiers(); // Remove final modifier from field Field modifiersField = Field.class.getDeclaredField("modifiers"); modifiersField.setAccessible(true); modifiersField.setInt(field, existingModifiers & ~Modifier.FINAL); field.set(null, newValue); // Reset previous modifiers modifiersField.setInt(field, existingModifiers); }
From source file:org.jenkinsci.plugins.ghprb.GhprbTestUtil.java
static void setFinal(Object o, Field field, Object newValue) throws Exception { field.setAccessible(true);/*from w w w.j a v a 2 s . c o m*/ Field modifiersField = Field.class.getDeclaredField("modifiers"); modifiersField.setAccessible(true); int prevModifiers = field.getModifiers(); modifiersField.setInt(field, prevModifiers & ~Modifier.FINAL); field.set(o, newValue); modifiersField.setInt(field, prevModifiers); modifiersField.setAccessible(false); field.setAccessible(false); }
From source file:ryerson.daspub.Config.java
/** * Parse arguments and assign variables// ww w .j a va 2 s.c o m * @param Args */ private static void setValues(HashMap<String, String> Args) { Set<String> keys = Args.keySet(); Iterator<String> it = keys.iterator(); String name = ""; String val = ""; Field field = null; while (it.hasNext()) { name = it.next(); // all local fields have upper case names Class aClass = Config.class; try { field = aClass.getField(name.toUpperCase()); val = Args.get(name); if (field.getType() == int.class) { field.setInt(Config.class, Integer.valueOf(val)); } else { field.set(Config.class, val); } logger.log(Level.INFO, "Set \"{0}\" as \"{1}\"", new Object[] { field.getName(), val.toString() }); } catch (Exception ex) { String stack = ExceptionUtils.getStackTrace(ex); logger.log(Level.SEVERE, "Could not find or set field \"{0}\"\n\n{1}", new Object[] { name, stack }); } } // create derived objects if (ARCHIVE_PATH != null && ARCHIVE_PATH.contains(";")) { String[] items = ARCHIVE_PATH.split(";"); for (int i = 0; i < items.length; i++) { String path = items[i].trim(); ARCHIVE_PATHS.add(path); } } else { ARCHIVE_PATHS.add(ARCHIVE_PATH); } }
From source file:org.janusgraph.diskstorage.cql.CassandraStorageSetup.java
private static void setWrapperStoreManager() { try {/*from ww w. j a v a 2 s . c o m*/ final Field modifiersField = Field.class.getDeclaredField("modifiers"); modifiersField.setAccessible(true); Field field = StandardStoreManager.class.getDeclaredField("managerClass"); field.setAccessible(true); field.set(StandardStoreManager.CQL, CachingCQLStoreManager.class.getCanonicalName()); field = StandardStoreManager.class.getDeclaredField("ALL_SHORTHANDS"); field.setAccessible(true); modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL); field.set(null, ImmutableList.copyOf(StandardStoreManager.CQL.getShorthands())); field = StandardStoreManager.class.getDeclaredField("ALL_MANAGER_CLASSES"); field.setAccessible(true); modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL); field.set(null, ImmutableMap.of(StandardStoreManager.CQL.getShorthands().get(0), StandardStoreManager.CQL.getManagerClass())); } catch (ReflectiveOperationException e) { throw new RuntimeException("Unable to set wrapper CQL store manager", e); } }
From source file:com.fjn.helper.common.io.file.common.FileUpAndDownloadUtil.java
/** * ???????/*from ww w . j ava2s.co m*/ * @param klass ???klass?Class * @param filepath ? * @param sizeThreshold ?? * @param isFileNameBaseTime ???? * @return bean */ public static <T> Object upload(HttpServletRequest request, Class<T> klass, String filepath, int sizeThreshold, boolean isFileNameBaseTime) throws Exception { FileItemFactory fileItemFactory = null; if (sizeThreshold > 0) { File repository = new File(filepath); fileItemFactory = new DiskFileItemFactory(sizeThreshold, repository); } else { fileItemFactory = new DiskFileItemFactory(); } ServletFileUpload upload = new ServletFileUpload(fileItemFactory); ServletRequestContext requestContext = new ServletRequestContext(request); T bean = null; if (klass != null) { bean = klass.newInstance(); } // if (ServletFileUpload.isMultipartContent(requestContext)) { File parentDir = new File(filepath); List<FileItem> fileItemList = upload.parseRequest(requestContext); for (int i = 0; i < fileItemList.size(); i++) { FileItem item = fileItemList.get(i); // ?? if (item.isFormField()) { String paramName = item.getFieldName(); String paramValue = item.getString("UTF-8"); log.info("?" + paramName + "=" + paramValue); request.setAttribute(paramName, paramValue); // ?bean if (klass != null) { Field field = null; try { field = klass.getDeclaredField(paramName); if (field != null) { field.setAccessible(true); Class type = field.getType(); if (type == Integer.TYPE) { field.setInt(bean, Integer.valueOf(paramValue)); } else if (type == Double.TYPE) { field.setDouble(bean, Double.valueOf(paramValue)); } else if (type == Float.TYPE) { field.setFloat(bean, Float.valueOf(paramValue)); } else if (type == Boolean.TYPE) { field.setBoolean(bean, Boolean.valueOf(paramValue)); } else if (type == Character.TYPE) { field.setChar(bean, paramValue.charAt(0)); } else if (type == Long.TYPE) { field.setLong(bean, Long.valueOf(paramValue)); } else if (type == Short.TYPE) { field.setShort(bean, Short.valueOf(paramValue)); } else { field.set(bean, paramValue); } } } catch (NoSuchFieldException e) { log.info("" + klass.getName() + "?" + paramName); } } } // else { // <input type='file' name='xxx'> xxx String paramName = item.getFieldName(); log.info("?" + item.getSize()); if (sizeThreshold > 0) { if (item.getSize() > sizeThreshold) continue; } String clientFileName = item.getName(); int index = -1; // ?IE? if ((index = clientFileName.lastIndexOf("\\")) != -1) { clientFileName = clientFileName.substring(index + 1); } if (clientFileName == null || "".equals(clientFileName)) continue; String filename = null; log.info("" + paramName + "\t??" + clientFileName); if (isFileNameBaseTime) { filename = buildFileName(clientFileName); } else filename = clientFileName; request.setAttribute(paramName, filename); // ?bean if (klass != null) { Field field = null; try { field = klass.getDeclaredField(paramName); if (field != null) { field.setAccessible(true); field.set(bean, filename); } } catch (NoSuchFieldException e) { log.info("" + klass.getName() + "? " + paramName); continue; } } if (!parentDir.exists()) { parentDir.mkdirs(); } File newfile = new File(parentDir, filename); item.write(newfile); String serverPath = newfile.getPath(); log.info("?" + serverPath); } } } return bean; }
From source file:org.rhq.core.domain.server.PersistenceUtility.java
@SuppressWarnings("unchecked") // used in hibernate.jsp public static Object cast(String value, Type hibernateType) { if (hibernateType instanceof PrimitiveType) { Class<?> type = ((PrimitiveType) hibernateType).getPrimitiveClass(); if (type.equals(Byte.TYPE)) { return Byte.valueOf(value); } else if (type.equals(Short.TYPE)) { return Short.valueOf(value); } else if (type.equals(Integer.TYPE)) { return Integer.valueOf(value); } else if (type.equals(Long.TYPE)) { return Long.valueOf(value); } else if (type.equals(Float.TYPE)) { return Float.valueOf(value); } else if (type.equals(Double.TYPE)) { return Double.valueOf(value); } else if (type.equals(Boolean.TYPE)) { return Boolean.valueOf(value); }//from w w w .j av a 2 s. c om } else if (hibernateType instanceof EntityType) { String entityName = ((EntityType) hibernateType).getAssociatedEntityName(); try { Class<?> entityClass = Class.forName(entityName); Object entity = entityClass.newInstance(); Field primaryKeyField = entityClass.getDeclaredField("id"); primaryKeyField.setAccessible(true); primaryKeyField.setInt(entity, Integer.valueOf(value)); return entity; } catch (Throwable t) { throw new IllegalArgumentException("Type[" + entityName + "] must have PK field named 'id'"); } } else if (hibernateType instanceof CustomType) { if (Enum.class.isAssignableFrom(hibernateType.getReturnedClass())) { Class<? extends Enum<?>> enumClass = hibernateType.getReturnedClass(); Enum<?>[] enumValues = enumClass.getEnumConstants(); try { int enumOrdinal = Integer.valueOf(value); try { return enumValues[enumOrdinal]; } catch (ArrayIndexOutOfBoundsException aioobe) { throw new IllegalArgumentException("There is no " + enumClass.getSimpleName() + " enum with ordinal '" + enumOrdinal + "'"); } } catch (NumberFormatException nfe) { String ucaseValue = value.toUpperCase(); for (Enum<?> nextEnum : enumValues) { if (nextEnum.name().toUpperCase().equals(ucaseValue)) { return nextEnum; } } throw new IllegalArgumentException( "There is no " + enumClass.getSimpleName() + " enum with name '" + value + "'"); } } } return value; }
From source file:io.github.wysohn.triggerreactor.tools.ReflectionUtil.java
/** * https://stackoverflow.com/questions/3301635/change-private-static-final-field-using-java-reflection * @param field// w w w. j a va2 s . co m * @param newValue * @throws SecurityException * @throws NoSuchFieldException * @throws Exception */ private static void setFinalField(Object target, Field field, Object newValue) throws NoSuchFieldException { field.setAccessible(true); Field modifiersField = null; try { modifiersField = Field.class.getDeclaredField("modifiers"); } catch (SecurityException e1) { e1.printStackTrace(); } modifiersField.setAccessible(true); try { modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL); } catch (IllegalArgumentException | IllegalAccessException e) { e.printStackTrace(); } try { field.set(target, newValue); } catch (IllegalAccessException e) { e.printStackTrace(); } }
From source file:org.apache.tika.server.resource.TikaResource.java
/** * Utility method to set a property on a class via reflection. * * @param httpHeaders the HTTP headers set. * @param object the <code>Object</code> to set the property on. * @param key the key of the HTTP Header. * @param prefix the name of the HTTP Header prefix used to find property. * @throws WebApplicationException thrown when field cannot be found. */// w ww . j av a2 s. co m private static void processHeaderConfig(MultivaluedMap<String, String> httpHeaders, Object object, String key, String prefix) { try { String property = StringUtils.removeStart(key, prefix); Field field = object.getClass().getDeclaredField(StringUtils.uncapitalize(property)); field.setAccessible(true); if (field.getType() == String.class) { field.set(object, httpHeaders.getFirst(key)); } else if (field.getType() == int.class) { field.setInt(object, Integer.parseInt(httpHeaders.getFirst(key))); } else if (field.getType() == double.class) { field.setDouble(object, Double.parseDouble(httpHeaders.getFirst(key))); } else if (field.getType() == boolean.class) { field.setBoolean(object, Boolean.parseBoolean(httpHeaders.getFirst(key))); } else { //couldn't find a directly accessible field //try for setX(String s) String setter = StringUtils.uncapitalize(property); setter = "set" + setter.substring(0, 1).toUpperCase(Locale.US) + setter.substring(1); Method m = null; try { m = object.getClass().getMethod(setter, String.class); } catch (NoSuchMethodException e) { //swallow } if (m != null) { m.invoke(object, httpHeaders.getFirst(key)); } } } catch (Throwable ex) { throw new WebApplicationException( String.format(Locale.ROOT, "%s is an invalid %s header", key, X_TIKA_OCR_HEADER_PREFIX)); } }