List of usage examples for java.lang.reflect Field set
@CallerSensitive @ForceInline public void set(Object obj, Object value) throws IllegalArgumentException, IllegalAccessException
From source file:org.cybercat.automation.annotations.AnnotationBuilder.java
/** * @param targetObject//ww w. ja va2s . c o m * @param fields * @param i * @throws AutomationFrameworkException */ public static void processPropertyField(Object targetObject, Field field) throws AutomationFrameworkException { try { CCProperty properties = field.getAnnotation(CCProperty.class); StringBuffer value = new StringBuffer(""); for (String prop : properties.value()) { value.append(AutomationMain.getProperty(prop)); } field.set(targetObject, value.toString()); } catch (Exception e) { throw new AutomationFrameworkException( "Set filed exception. Please, save this log and contact the Cybercat project support." + " field name: " + field.getName() + " class: " + targetObject.getClass().getSimpleName() + " Thread ID:" + Thread.currentThread().getId(), e); } }
From source file:com.bosscs.spark.commons.utils.Utils.java
/** * @param object/*from w ww.ja v a 2 s .co m*/ * @param fieldName * @param fieldValue * @return if the operation has been correct. */ public static boolean setFieldWithReflection(Object object, String fieldName, Object fieldValue) { Class<?> clazz = object.getClass(); while (clazz != null) { try { Field field = clazz.getDeclaredField(fieldName); field.setAccessible(true); field.set(object, fieldValue); return true; } catch (NoSuchFieldException e) { clazz = clazz.getSuperclass(); } catch (Exception e) { throw new IllegalStateException(e); } } return false; }
From source file:ml.dmlc.xgboost4j.java.NativeLibLoader.java
/** * Add libPath to java.library.path, then native library in libPath would be load properly * * @param libPath library path/* ww w. j a v a 2 s . c o m*/ * @throws IOException exception */ private static void addNativeDir(String libPath) throws IOException { try { Field field = ClassLoader.class.getDeclaredField("usr_paths"); field.setAccessible(true); String[] paths = (String[]) field.get(null); for (String path : paths) { if (libPath.equals(path)) { return; } } String[] tmp = new String[paths.length + 1]; System.arraycopy(paths, 0, tmp, 0, paths.length); tmp[paths.length] = libPath; field.set(null, tmp); } catch (IllegalAccessException e) { logger.error(e.getMessage()); throw new IOException("Failed to get permissions to set library path"); } catch (NoSuchFieldException e) { logger.error(e.getMessage()); throw new IOException("Failed to get field handle to set library path"); } }
From source file:com.jilk.ros.rosbridge.implementation.JSON.java
private static Message convertJSONArrayToMessage(JSONArray ja, Class c, Registry<Class> r) { try {/*from w ww .j av a 2 s . c om*/ Message result = (Message) c.newInstance(); int arrayIndex = 0; for (Field f : c.getFields()) { Class fc = getFieldClass(result, null, f, r); Object lookup = ja.get(arrayIndex++); // yes we are assuming that the fields are delivered in order if (lookup != null) { Object value = convertElementToField(lookup, fc, f, r); f.set(result, value); } } return result; } catch (Exception ex) { ex.printStackTrace(); return null; } }
From source file:com.taobao.android.builder.tools.guide.AtlasConfigHelper.java
public static void setProperty(Object object, String fieldName, String value) throws IllegalAccessException, InstantiationException, InvocationTargetException, NoSuchFieldException { String[] fieldNames = fieldName.split("\\."); Object last = object;/* w ww.jav a2s . com*/ for (int i = 0; i < fieldNames.length - 1; i++) { String field = fieldNames[i]; if (last instanceof NamedDomainObjectContainer) { last = ((NamedDomainObjectContainer) last).maybeCreate(field); } else { Field declaredField = last.getClass().getField(field); declaredField.setAccessible(true); if (null == declaredField.get(last)) { Object newInstance = declaredField.getType().getConstructors().getClass().newInstance(); declaredField.set(last, newInstance); } last = declaredField.get(last); } } BeanUtils.setProperty(last, fieldNames[fieldNames.length - 1], value); }
From source file:net.ostis.sc.memory.SCKeynodesBase.java
private static boolean checkKeynodeURI(SCSession session, Field field) throws IllegalArgumentException, IllegalAccessException { KeynodeURI keynodeURI = field.getAnnotation(KeynodeURI.class); if (keynodeURI != null) { String[] comp = URIUtils.splitByIdtf(keynodeURI.value()); SCSegment segment = session.openSegment(comp[0]); SCAddr keynode = session.findByIdtf(comp[1], segment); Validate.notNull(keynode);// w ww . j av a 2s . c om field.set(null, keynode); if (log.isDebugEnabled()) log.debug(keynodeURI.value() + " --> " + field.getName()); return true; } else { return false; } }
From source file:hivemall.xgboost.NativeLibLoader.java
/** * Add libPath to java.library.path, then native library in libPath would be load properly. * * @param libPath library path//from w ww . j a v a 2 s. c o m * @throws IOException exception */ private static void addLibraryPath(String libPath) throws IOException { try { final Field field = ClassLoader.class.getDeclaredField("usr_paths"); field.setAccessible(true); final String[] paths = (String[]) field.get(null); for (String path : paths) { if (libPath.equals(path)) { return; } } final String[] tmp = new String[paths.length + 1]; System.arraycopy(paths, 0, tmp, 0, paths.length); tmp[paths.length] = libPath; field.set(null, tmp); } catch (IllegalAccessException e) { logger.error(e.getMessage()); throw new IOException("Failed to get permissions to set library path"); } catch (NoSuchFieldException e) { logger.error(e.getMessage()); throw new IOException("Failed to get field handle to set library path"); } }
From source file:de.micromata.genome.util.runtime.ClassUtils.java
/** * Set all String field to empty on current class. * * @param object the object/* w w w. j av a2 s . c om*/ * @param exceptClass the except class * @throws IllegalArgumentException the illegal argument exception * @throws IllegalAccessException the illegal access exception */ // CHECKSTYLE.OFF com.puppycrawl.tools.checkstyle.checks.metrics.CyclomaticComplexityCheck Trivial code. public static void fillDefaultEmptyFieldsIfEmpty(Object object, Class<?>... exceptClass) // NOSONAR "Methods should not be too complex" trivial throws IllegalArgumentException, IllegalAccessException { Class<?> currentClazz = object.getClass(); List exClazzes = Arrays.asList(exceptClass); while (currentClazz.getSuperclass() != null) { if (exClazzes.contains(currentClazz) == false) { Field[] fields = currentClazz.getDeclaredFields(); for (Field field : fields) { if (String.class.equals(field.getType())) { field.setAccessible(true); if (field.get(object) == null) { field.set(object, ""); } } if (Integer.class.equals(field.getType())) { field.setAccessible(true); if (field.get(object) == null) { field.set(object, 0); } } if (BigDecimal.class.equals(field.getType())) { field.setAccessible(true); if (field.get(object) == null) { field.set(object, BigDecimal.ZERO); } } if (Date.class.equals(field.getType())) { field.setAccessible(true); if (field.get(object) == null) { field.set(object, new Date()); } } } } currentClazz = currentClazz.getSuperclass(); } }
From source file:tools.xor.util.ClassUtil.java
/** * Invoke the given method as a privileged action, if necessary. * @param target the object on which the method needs to be invoked * @param field we are reading or writing * @param value to set in the field/*w w w . j av a 2 s . com*/ * @param read true if this a read operation * @return result of the invocation * @throws InvocationTargetException while invoking the method * @throws IllegalAccessException when accessing the meta data */ public static Object invokeFieldAsPrivileged(final Object target, final Field field, final Object value, final boolean read) throws InvocationTargetException, IllegalAccessException { if (Modifier.isPublic(field.getModifiers())) { Object readValue = null; if (read) readValue = field.get(target); else field.set(target, value); return readValue; } else { return AccessController.doPrivileged(new PrivilegedAction<Object>() { public Object run() { field.setAccessible(true); Object readValue = null; try { if (read) readValue = field.get(target); else field.set(target, value); } catch (Exception e) { throw wrapRun(e); } return readValue; } }); } }
From source file:com.initialxy.cordova.themeablebrowser.ThemeableBrowserUnmarshaller.java
/** * Given a JSONObject, unmarhall it to an instance of the given class. * * @param jsonObj JSON string to unmarshall. * @param cls Return an instance of this class. Must be either public class * or private static class. Inner class will not work. * @param <T> Same type as cls.//from w w w . j a va2s. com * @return An instance of class given by cls. * @throws com.initialxy.cordova.themeablebrowser.ThemeableBrowserUnmarshaller.TypeMismatchException */ public static <T> T JSONToObj(JSONObject jsonObj, Class<T> cls) { T result = null; try { Constructor<T> constructor = cls.getDeclaredConstructor(); constructor.setAccessible(true); result = (T) constructor.newInstance(); Iterator<?> i = jsonObj.keys(); while (i.hasNext()) { String k = (String) i.next(); Object val = jsonObj.get(k); try { Field field = cls.getField(k); Object converted = valToType(val, field.getGenericType()); if (converted == null) { if (!field.getType().isPrimitive()) { field.set(result, null); } else { throw new TypeMismatchException( String.format("Type %s cannot be set to null.", field.getType())); } } else { if (converted instanceof List && field.getType().isAssignableFrom(List.class)) { // Class can define their own favorite // implementation of List. In which case the field // still need to be defined as List, but it can be // initialized with a placeholder instance of any of // the List implementations (eg. ArrayList). Object existing = field.get(result); if (existing != null) { ((List<?>) existing).clear(); // Just because I don't want javac to complain // about unsafe operations. So I'm gonna use // more reflection, HA! Method addAll = existing.getClass().getMethod("addAll", Collection.class); addAll.invoke(existing, converted); } else { field.set(result, converted); } } else { field.set(result, converted); } } } catch (NoSuchFieldException e) { // Ignore. } catch (IllegalAccessException e) { // Ignore. } catch (IllegalArgumentException e) { // Ignore. } } } catch (JSONException e) { throw new ParserException(e); } catch (NoSuchMethodException e) { throw new ClassInstantiationException("Failed to retrieve constructor for " + cls.toString() + ", make sure it's not an inner class."); } catch (InstantiationException e) { throw new ClassInstantiationException(cls); } catch (IllegalAccessException e) { throw new ClassInstantiationException(cls); } catch (InvocationTargetException e) { throw new ClassInstantiationException(cls); } return result; }