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:io.pivotal.spring.xd.jdbcgpfdist.TestUtils.java
public static void setField(String name, Object target, Object value) throws Exception { Field field = null; Class<?> clazz = target.getClass(); do {/* ww w . j a v a 2s .c om*/ try { field = clazz.getDeclaredField(name); } catch (Exception ex) { } clazz = clazz.getSuperclass(); } while (field == null && !clazz.equals(Object.class)); if (field == null) throw new IllegalArgumentException( "Cannot find field '" + name + "' in the class hierarchy of " + target.getClass()); field.setAccessible(true); field.set(target, value); }
From source file:info.donsun.core.utils.Reflections.java
/** * , private/protected, ??setter./* w w w. j a v a 2 s. com*/ */ public static void setFieldValue(final Class<?> clazz, final String fieldName, final Object value) { Field field = getAccessibleField(clazz, fieldName); if (field == null) { throw new IllegalArgumentException( "Could not find field [" + fieldName + "] on target [" + clazz + "]"); } try { field.set(clazz, value); } catch (IllegalAccessException e) { logger.error("setFieldValue:{}", e.getMessage()); } }
From source file:com.gson.WeChat.java
/** * ???//from ww w. j av a 2s . c o m * @param oms * @param msg * @throws Exception */ private static void setMsgInfo(OutMessage oms, InMessage msg) throws Exception { if (oms != null) { Class<?> outMsg = oms.getClass().getSuperclass(); Field CreateTime = outMsg.getDeclaredField("CreateTime"); Field ToUserName = outMsg.getDeclaredField("ToUserName"); Field FromUserName = outMsg.getDeclaredField("FromUserName"); ToUserName.setAccessible(true); CreateTime.setAccessible(true); FromUserName.setAccessible(true); CreateTime.set(oms, new Date().getTime()); ToUserName.set(oms, msg.getFromUserName()); FromUserName.set(oms, msg.getToUserName()); } }
From source file:com.braffdev.server.core.container.injection.DependencyInjector.java
/** * Injects the given dependency to the given field of the given object. * * @param field the field to inject.//from www . j av a 2s . co m * @param target the object. * @param dependencyName the name of the dependency. * @param dependency the dependency to inject. */ private static void injectFieldDependency(Field field, Object target, String dependencyName, Object dependency) { Class<?> fieldClass = field.getType(); if (!dependency.getClass().isAssignableFrom(fieldClass)) { LOGGER.error("Dependency \"" + dependencyName + "\" (class " + dependency.getClass().getName() + ") cannot be injected. This class is not assignable from the target field"); return; } try { field.setAccessible(true); field.set(target, dependency); LOGGER.debug("Injected dependency \"" + dependencyName + "\" of class \"" + target.getClass() + "\""); } catch (Throwable t) { LOGGER.error("Cannot inject dependency \"" + dependencyName + "\"", t); } }
From source file:edu.mit.csail.sdg.alloy4.Terminal.java
/** Copy the required files from the JAR into a temporary directory. */ private static void copyFromJAR() { // Compute the appropriate platform String os = System.getProperty("os.name").toLowerCase(Locale.US).replace(' ', '-'); if (os.startsWith("mac-")) os = "mac"; else if (os.startsWith("windows-")) os = "windows"; String arch = System.getProperty("os.arch").toLowerCase(Locale.US).replace(' ', '-'); if (arch.equals("powerpc")) arch = "ppc-" + os; else/*from w w w . j av a 2s.com*/ arch = arch.replaceAll("\\Ai[3456]86\\z", "x86") + "-" + os; if (os.equals("mac")) arch = "x86-mac"; // our pre-compiled binaries are all universal binaries // Find out the appropriate Alloy directory final String platformBinary = alloyHome() + fs + "binary"; // Write a few test files try { (new File(platformBinary)).mkdirs(); Util.writeAll(platformBinary + fs + "tmp.cnf", "p cnf 3 1\n1 0\n"); } catch (Err er) { // The error will be caught later by the "berkmin" or "spear" test } // Copy the platform-dependent binaries Util.copy(true, false, platformBinary, arch + "/libminisat.so", arch + "/libminisatx1.so", arch + "/libminisat.jnilib", arch + "/libminisatprover.so", arch + "/libminisatproverx1.so", arch + "/libminisatprover.jnilib", arch + "/libzchaff.so", arch + "/libzchaffx1.so", arch + "/libzchaff.jnilib", arch + "/berkmin", arch + "/spear"); Util.copy(false, false, platformBinary, arch + "/minisat.dll", arch + "/minisatprover.dll", arch + "/zchaff.dll", arch + "/berkmin.exe", arch + "/spear.exe"); // Copy the model files Util.copy(false, true, alloyHome(), "models/book/appendixA/addressBook1.als", "models/book/appendixA/addressBook2.als", "models/book/appendixA/barbers.als", "models/book/appendixA/closure.als", "models/book/appendixA/distribution.als", "models/book/appendixA/phones.als", "models/book/appendixA/prison.als", "models/book/appendixA/properties.als", "models/book/appendixA/ring.als", "models/book/appendixA/spanning.als", "models/book/appendixA/tree.als", "models/book/appendixA/tube.als", "models/book/appendixA/undirected.als", "models/book/appendixE/hotel.thm", "models/book/appendixE/p300-hotel.als", "models/book/appendixE/p303-hotel.als", "models/book/appendixE/p306-hotel.als", "models/book/chapter2/addressBook1a.als", "models/book/chapter2/addressBook1b.als", "models/book/chapter2/addressBook1c.als", "models/book/chapter2/addressBook1d.als", "models/book/chapter2/addressBook1e.als", "models/book/chapter2/addressBook1f.als", "models/book/chapter2/addressBook1g.als", "models/book/chapter2/addressBook1h.als", "models/book/chapter2/addressBook2a.als", "models/book/chapter2/addressBook2b.als", "models/book/chapter2/addressBook2c.als", "models/book/chapter2/addressBook2d.als", "models/book/chapter2/addressBook2e.als", "models/book/chapter2/addressBook3a.als", "models/book/chapter2/addressBook3b.als", "models/book/chapter2/addressBook3c.als", "models/book/chapter2/addressBook3d.als", "models/book/chapter2/theme.thm", "models/book/chapter4/filesystem.als", "models/book/chapter4/grandpa1.als", "models/book/chapter4/grandpa2.als", "models/book/chapter4/grandpa3.als", "models/book/chapter4/lights.als", "models/book/chapter5/addressBook.als", "models/book/chapter5/lists.als", "models/book/chapter5/sets1.als", "models/book/chapter5/sets2.als", "models/book/chapter6/hotel.thm", "models/book/chapter6/hotel1.als", "models/book/chapter6/hotel2.als", "models/book/chapter6/hotel3.als", "models/book/chapter6/hotel4.als", "models/book/chapter6/mediaAssets.als", "models/book/chapter6/memory/abstractMemory.als", "models/book/chapter6/memory/cacheMemory.als", "models/book/chapter6/memory/checkCache.als", "models/book/chapter6/memory/checkFixedSize.als", "models/book/chapter6/memory/fixedSizeMemory.als", "models/book/chapter6/memory/fixedSizeMemory_H.als", "models/book/chapter6/ringElection.thm", "models/book/chapter6/ringElection1.als", "models/book/chapter6/ringElection2.als", "models/examples/algorithms/dijkstra.als", "models/examples/algorithms/dijkstra.thm", "models/examples/algorithms/messaging.als", "models/examples/algorithms/messaging.thm", "models/examples/algorithms/opt_spantree.als", "models/examples/algorithms/opt_spantree.thm", "models/examples/algorithms/peterson.als", "models/examples/algorithms/ringlead.als", "models/examples/algorithms/ringlead.thm", "models/examples/algorithms/s_ringlead.als", "models/examples/algorithms/stable_mutex_ring.als", "models/examples/algorithms/stable_mutex_ring.thm", "models/examples/algorithms/stable_orient_ring.als", "models/examples/algorithms/stable_orient_ring.thm", "models/examples/algorithms/stable_ringlead.als", "models/examples/algorithms/stable_ringlead.thm", "models/examples/case_studies/INSLabel.als", "models/examples/case_studies/chord.als", "models/examples/case_studies/chord2.als", "models/examples/case_studies/chordbugmodel.als", "models/examples/case_studies/com.als", "models/examples/case_studies/firewire.als", "models/examples/case_studies/firewire.thm", "models/examples/case_studies/ins.als", "models/examples/case_studies/iolus.als", "models/examples/case_studies/sync.als", "models/examples/case_studies/syncimpl.als", "models/examples/puzzles/farmer.als", "models/examples/puzzles/farmer.thm", "models/examples/puzzles/handshake.als", "models/examples/puzzles/handshake.thm", "models/examples/puzzles/hanoi.als", "models/examples/puzzles/hanoi.thm", "models/examples/systems/file_system.als", "models/examples/systems/file_system.thm", "models/examples/systems/javatypes_soundness.als", "models/examples/systems/lists.als", "models/examples/systems/lists.thm", "models/examples/systems/marksweepgc.als", "models/examples/systems/views.als", "models/examples/toys/birthday.als", "models/examples/toys/birthday.thm", "models/examples/toys/ceilingsAndFloors.als", "models/examples/toys/ceilingsAndFloors.thm", "models/examples/toys/genealogy.als", "models/examples/toys/genealogy.thm", "models/examples/toys/grandpa.als", "models/examples/toys/grandpa.thm", "models/examples/toys/javatypes.als", "models/examples/toys/life.als", "models/examples/toys/life.thm", "models/examples/toys/numbering.als", "models/examples/toys/railway.als", "models/examples/toys/railway.thm", "models/examples/toys/trivial.als", "models/examples/tutorial/farmer.als", "models/util/boolean.als", "models/util/graph.als", "models/util/integer.als", "models/util/natural.als", "models/util/ordering.als", "models/util/relation.als", "models/util/seqrel.als", "models/util/sequence.als", "models/util/sequniv.als", "models/util/ternary.als", "models/util/time.als"); // Record the locations System.setProperty("alloy.theme0", alloyHome() + fs + "models"); System.setProperty("alloy.home", alloyHome()); try { // It doesn't work to set the env variable after java is started but this hack makes it work see // http://blog.cedarsoft.com/2010/11/setting-java-library-path-programmatically/ System.setProperty("java.library.path", platformBinary); Field fieldSysPath = ClassLoader.class.getDeclaredField("sys_paths"); fieldSysPath.setAccessible(true); fieldSysPath.set(null, null); } catch (SecurityException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NoSuchFieldException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalArgumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
From source file:com.evolveum.midpoint.repo.sql.util.RUtil.java
private static void fixCompositeIdentifierInMetaModel(SessionFactory sessionFactory, Class clazz) { ClassMetadata classMetadata = sessionFactory.getClassMetadata(clazz); if (classMetadata instanceof AbstractEntityPersister) { AbstractEntityPersister persister = (AbstractEntityPersister) classMetadata; EntityMetamodel model = persister.getEntityMetamodel(); IdentifierProperty identifier = model.getIdentifierProperty(); try {//w w w. j av a 2s . c o m Field field = IdentifierProperty.class.getDeclaredField("hasIdentifierMapper"); field.setAccessible(true); field.set(identifier, true); field.setAccessible(false); } catch (Exception ex) { throw new SystemException( "Attempt to fix entity meta model with hack failed, reason: " + ex.getMessage(), ex); } } }
From source file:com.fengduo.bee.commons.util.ObjectUtils.java
/** * string?trim?//ww w . ja v a2 s.c o m * * @param object * @throws Exception */ @SuppressWarnings({ "unchecked", "rawtypes" }) private static void trimStringField(Object object, Class<?> clazz) throws Exception { if (object instanceof Map<?, ?>) { Map<Object, Object> target = new HashMap<Object, Object>(); for (Entry<?, ?> entry : ((Map<?, ?>) object).entrySet()) { Object key = entry.getKey(); Object value = entry.getValue(); if (key instanceof String) { key = StringUtils.trim((String) key); } else { trim(key); } if (value instanceof String) { value = StringUtils.trim((String) value); value = StringUtils.replace((String) value, "\"", StringUtils.EMPTY); } else { trim(value); } target.put(key, value); } ((Map<?, ?>) object).clear(); ((Map) object).putAll((Map) target); return; } Field[] fields = clazz.getDeclaredFields(); for (Field field : fields) { if (field.getType() == String.class) { boolean isFoolback = false; if (field.isAccessible() == false) { isFoolback = true; field.setAccessible(true); } String value = (String) field.get(object); if (StringUtils.isNotEmpty(value)) { value = value.trim(); field.set(object, value); } if (isFoolback) { field.setAccessible(false); } } } }
From source file:com.mh.commons.utils.Reflections.java
/** * , private/protected, ??setter./* w w w.j av a2 s . c om*/ */ public static void setFieldValue(final Object object, final String fieldName, final Object value) { Field field = getDeclaredField(object, fieldName); if (field == null) { throw new IllegalArgumentException( "Could not find field [" + fieldName + "] on target [" + object + "]"); } makeAccessible(field); try { field.set(object, value); } catch (IllegalAccessException e) { if (logger.isDebugEnabled()) { logger.error("" + e.getMessage() + ", [ReflectionUtils.setFieldValue]", e); } } }
From source file:com.plusub.lib.annotate.JsonParserUtils.java
/** * /*www. j a va2 s . c om*/ * <p>Title: setFieldValue * <p>Description: * @param object * @param field * @param value */ private static void setFieldValue(Object object, Field field, Object value) { Object ov = null; try { ov = getType(field, value, field.getName()); field.set(object, ov); } catch (IllegalAccessException e) { // TODO Auto-generated catch block if (showLog) { e.printStackTrace(); } //fieldset try { Method m = object.getClass().getMethod(getSetMethodName(field), field.getType()); if (m != null) { m.invoke(object, ov); } } catch (Exception e1) { // TODO Auto-generated catch block if (showLog) { Logger.e(TAG, "set field value fail field:" + field.getName() + " method:" + getSetMethodName(field)); e1.printStackTrace(); } } } catch (IllegalArgumentException e) { // TODO Auto-generated catch block if (showLog) { e.printStackTrace(); } } catch (Exception e) { if (showLog) { e.printStackTrace(); } } }
From source file:com.yahoo.egads.data.JsonEncoder.java
public static void fromJson(Object object, JSONObject json_obj) throws Exception { // for each json key-value, that has a corresponding variable in object ... for (Iterator k = json_obj.keys(); k.hasNext();) { String key = (String) k.next(); Object value = json_obj.get(key); // try to access object variable Field field = null; try {/*from w w w . j a v a 2s.c om*/ field = object.getClass().getField(key); } catch (Exception e) { continue; } if (Modifier.isStatic(field.getModifiers())) { continue; } if (Modifier.isPrivate(field.getModifiers())) { continue; } Object member = field.get(object); if (json_obj.isNull(key)) { field.set(object, null); continue; // if variable is container... recurse } else if (member instanceof JsonAble) { ((JsonAble) member).fromJson((JSONObject) value); // if variable is an array... recurse on sub-objects } else if (member instanceof ArrayList) { // Depends on existance of ArrayList<T> template parameter, and T constructor with no arguments. // May be better to use custom fromJson() in member class. ArrayList memberArray = (ArrayList) member; JSONArray jsonArray = (JSONArray) value; // find array element constructor ParameterizedType arrayType = null; if (field.getGenericType() instanceof ParameterizedType) { arrayType = (ParameterizedType) field.getGenericType(); } for (Class c = member.getClass(); arrayType == null && c != null; c = c.getSuperclass()) { if (c.getGenericSuperclass() instanceof ParameterizedType) { arrayType = (ParameterizedType) c.getGenericSuperclass(); } } if (arrayType == null) { throw new Exception("could not find ArrayList element type for field 'key'"); } Class elementClass = (Class) (arrayType.getActualTypeArguments()[0]); Constructor elementConstructor = elementClass.getConstructor(); // for each element in JSON array ... append element to member array, recursively decode element for (int i = 0; i < jsonArray.length(); ++i) { Object element = elementConstructor.newInstance(); fromJson(element, jsonArray.getJSONObject(i)); memberArray.add(element); } // if variable is simple value... set } else if (field.getType() == float.class) { field.set(object, (float) json_obj.getDouble(key)); } else { field.set(object, value); } } }