Java Code Examples for java.lang.reflect.Field#get()
The following examples show how to use
java.lang.reflect.Field#get() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ReflectAccelerator.java From Small with Apache License 2.0 | 6 votes |
public static Object getActivityThread(Context context) { try { Class activityThread = Class.forName("android.app.ActivityThread"); // ActivityThread.currentActivityThread() Method m = activityThread.getMethod("currentActivityThread", new Class[0]); m.setAccessible(true); Object thread = m.invoke(null, new Object[0]); if (thread != null) return thread; // context.@mLoadedApk.@mActivityThread Field mLoadedApk = context.getClass().getField("mLoadedApk"); mLoadedApk.setAccessible(true); Object apk = mLoadedApk.get(context); Field mActivityThreadField = apk.getClass().getDeclaredField("mActivityThread"); mActivityThreadField.setAccessible(true); return mActivityThreadField.get(apk); } catch (Throwable ignore) { throw new RuntimeException("Failed to get mActivityThread from context: " + context); } }
Example 2
Source File: MCRUserAttributeMapper.java From mycore with GNU General Public License v3.0 | 6 votes |
private Object getValue(final Object object, final Object annotated) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException, NoSuchMethodException, SecurityException { Object value = null; if (annotated instanceof Field) { final Field field = (Field) annotated; field.setAccessible(true); value = field.get(object); } else if (annotated instanceof Method) { Method method = null; String name = ((Method) annotated).getName(); if (name.startsWith("get")) { name = "s" + name.substring(1); method = object.getClass().getMethod(name); } if (method != null) { method.setAccessible(true); value = method.invoke(object); } } return value; }
Example 3
Source File: TestImportHandlerStandardPackages.java From Tomcat8-Source-Read with MIT License | 6 votes |
@Test public void testClassListsAreComplete() throws Exception { // Use reflection to get hold of the internal Map Class<?> clazz = ImportHandler.class; Field f = clazz.getDeclaredField("standardPackages"); f.setAccessible(true); Object obj = f.get(null); Assert.assertTrue("Not Map", obj instanceof Map); @SuppressWarnings("unchecked") Map<String,Set<String>> standardPackageName = (Map<String, Set<String>>) obj; for (Map.Entry<String,Set<String>> entry : standardPackageName.entrySet()) { checkPackageClassList(entry.getKey(), entry.getValue()); } }
Example 4
Source File: BaseDataBean.java From qaf with MIT License | 6 votes |
public String toCSV() { StringBuffer sb = new StringBuffer(); Field[] flds = this.getClass().getDeclaredFields(); for (Field fld : flds) { try { fld.setAccessible(true); if (fld.getDeclaringClass().equals(this.getClass()) && (fld.get(this) != null)) { sb.append(fld.get(this).toString()); } sb.append(","); } catch (Exception e) { e.printStackTrace(); } } return sb.toString(); }
Example 5
Source File: ExcelPrintSetupFactory.java From pentaho-reporting with GNU Lesser General Public License v2.1 | 5 votes |
/** * Searches all defined excel page formats to find a page format that matches the given pageformat. If no matching * format was found, the next greater page format is used. * <p/> * If no page format fits the definition, -1 is returned. * * @param format * the page format * @return the computed paper size or -1 if no paper size matches the requirements */ private static short computePaperSize( final PhysicalPageBox format ) { ExcelPageDefinition pageDef = null; final int width = (int) format.getWidth(); final int height = (int) format.getHeight(); int delta = -1; final Field[] fields = ExcelPrintSetupFactory.class.getDeclaredFields(); for ( int i = 0; i < fields.length; i++ ) { final Field field = fields[i]; if ( ExcelPageDefinition.class.isAssignableFrom( field.getType() ) == false ) { // Log.debug ("Is no valid pageformat definition"); continue; } if ( Modifier.isStatic( field.getModifiers() ) == false ) { // is no static field, who defined it here? continue; } try { final ExcelPageDefinition pageformat = (ExcelPageDefinition) field.get( null ); if ( ( pageformat.getWidth() < width ) || ( pageformat.getHeight() < height ) ) { // paper is too small, ignore it continue; } final int newDelta = ( pageformat.getWidth() - width ) + ( pageformat.getHeight() - height ); if ( ( delta == -1 ) || ( newDelta < delta ) ) { pageDef = pageformat; delta = newDelta; } } catch ( IllegalAccessException iae ) { // ignore .. } } if ( pageDef == null ) { return -1; } else { return pageDef.getPageFormatCode(); } }
Example 6
Source File: TestNoJGroupInit.java From dragonwell8_jdk with GNU General Public License v2.0 | 5 votes |
public static void main(String[] args) throws Exception { Class jgroupClazz = Class.forName("com.alibaba.tenant.NativeDispatcher"); Field f = jgroupClazz.getDeclaredField("CGROUP_INIT_SUCCESS"); f.setAccessible(true); Boolean b = (Boolean)f.get(null); if (b) { throw new RuntimeException("Should not be initialized!"); } }
Example 7
Source File: ImageViewHelper.java From simple_imageloader with MIT License | 5 votes |
private static int getImageViewFieldValue(Object object, String fieldName) { int value = 0; try { Field field = ImageView.class.getDeclaredField(fieldName); field.setAccessible(true); int fieldValue = (Integer) field.get(object); if (fieldValue > 0 && fieldValue < Integer.MAX_VALUE) { value = fieldValue; } } catch (Exception e) { Log.e("", e.getMessage()); } return value; }
Example 8
Source File: Persisted.java From commcare-android with Apache License 2.0 | 5 votes |
private static void writeVal(Field f, Object o, DataOutputStream out) throws IOException, IllegalAccessException { synchronized (f) { // 'f' is a cached field: sync access across threads try { Persisting p = f.getAnnotation(Persisting.class); Class type = f.getType(); f.setAccessible(true); if (type.equals(String.class)) { String s = (String)f.get(o); ExtUtil.writeString(out, p.nullable() ? ExtUtil.emptyIfNull(s) : s); return; } else if (type.equals(Integer.TYPE)) { ExtUtil.writeNumeric(out, f.getInt(o)); return; } else if (type.equals(Long.TYPE)) { ExtUtil.writeNumeric(out, f.getLong(o)); return; } else if (type.equals(Date.class)) { ExtUtil.writeDate(out, (Date)f.get(o)); return; } else if (type.isArray()) { //We only support byte arrays for now if (type.getComponentType().equals(Byte.TYPE)) { ExtUtil.writeBytes(out, (byte[])f.get(o)); return; } } else if (type.equals(Boolean.TYPE)) { ExtUtil.writeBool(out, f.getBoolean(o)); return; } } finally { f.setAccessible(false); } //By Default throw new RuntimeException("Couldn't write persisted type " + f.getType().toString()); } }
Example 9
Source File: CargoRepositoryTest.java From dddsample-core with MIT License | 5 votes |
private Long getLongId(Object o) { final Session session = sessionFactory.getCurrentSession(); if (session.contains(o)) { return (Long) session.getIdentifier(o); } else { try { Field id = o.getClass().getDeclaredField("id"); id.setAccessible(true); return (Long) id.get(o); } catch (Exception e) { throw new RuntimeException(); } } }
Example 10
Source File: CommonAnnotationBeanPostProcessor.java From brpc-java with Apache License 2.0 | 5 votes |
@Override protected void inject(Object bean, String beanName, PropertyValues pvs) throws Throwable { Field field = (Field) this.member; try { ReflectionUtils.makeAccessible(field); Object value = field.get(bean); value = getCallback().annotationAtField(annotation, value, beanName, pvs, beanFactory, field); if (value != null) { ReflectionUtils.makeAccessible(field); field.set(bean, value); } } catch (Throwable ex) { throw new BeanCreationException("Could not autowire field: " + field, ex); } }
Example 11
Source File: ClassUtils.java From iaf with Apache License 2.0 | 5 votes |
private static void appendFieldsAndMethods(StringBuffer result, Object o, String type, Class c) { Field fields[] = c.getDeclaredFields(); Method methods[] = c.getDeclaredMethods(); result.append(type+ " "+c.getName()+" #fields ["+fields.length+"] #methods ["+methods.length+"]"); if (fields.length>0 || methods.length>0) { result.append(" {\n"); for (int i=0; i<fields.length; i++) { Field f=fields[i]; Object value; try { f.setAccessible(true); value=f.get(o); } catch (Exception e) { value="Could not get value: "+ClassUtils.nameOf(e)+": "+e.getMessage(); } result.append(" field["+i+"] "+f.getName()+"("+f.getType().getName()+"): ["+value+"]\n"); } for (int i=0; i<methods.length; i++) { Method m=methods[i]; result.append(" method["+i+"] "+m.getName()); // Object value; // try { // m.setAccessible(true); // value=m.invoke(o,null); // } catch (Exception e) { // value="Could not get value: "+ClassUtils.nameOf(e)+": "+e.getMessage(); // } // result +=": ["+value+"]\n"; result.append("\n"); } result.append("}"); } result.append("\n"); }
Example 12
Source File: PreferencesDao.java From photoviewer with Apache License 2.0 | 5 votes |
private void putValueToEditor(SharedPreferences.Editor editor, String preferenceName, T model, Field field) { field.setAccessible(true); try { if (field.getType().equals(boolean.class)) { boolean booleanValue = field.getBoolean(model); editor.putBoolean(preferenceName, booleanValue); return; } if (field.getType().equals(int.class)) { int integerValue = field.getInt(model); editor.putInt(preferenceName, integerValue); return; } if (field.getType().equals(float.class)) { float floatValue = field.getFloat(model); editor.putFloat(preferenceName, floatValue); return; } if (field.getType().equals(long.class)) { long longValue = field.getLong(model); editor.putLong(preferenceName, longValue); return; } if (field.getType().equals(String.class)) { String stringValue = (String) field.get(model); editor.putString(preferenceName, stringValue); return; } Gson gson = new Gson(); editor.putString(preferenceName, gson.toJson(field.get(model))); } catch (IllegalAccessException e) { Log.wtf(TAG, "Exception during converting of Field's value to Preference", e); } }
Example 13
Source File: Util.java From openvisualtraceroute with GNU Lesser General Public License v3.0 | 5 votes |
public static String deepToString(final Object obj) { final StringBuilder sb = new StringBuilder(); if (obj != null) { Class<?> c = obj.getClass(); if (obj.getClass().isArray()) { if (obj.getClass() == byte[].class) { sb.append(Arrays.toString((byte[]) obj)); } else { sb.append(Arrays.toString((Object[]) obj)); } } else if (obj instanceof Number || obj instanceof Byte || obj instanceof Boolean || obj.getClass().isPrimitive() || obj instanceof String) { return obj.toString(); } else if (obj instanceof InetAddress) { return ((InetAddress) obj).getHostAddress(); } else { sb.append(obj.getClass().getSimpleName()).append("[ "); while (c != Object.class) { for (final Field f : c.getFields()) { if (!Modifier.isStatic(f.getModifiers())) { f.setAccessible(true); try { final Object o = f.get(obj); final String str = f.getType().isPrimitive() ? o.toString() : deepToString(o); sb.append(f.getName()).append("=").append(str).append(" "); } catch (final Exception e) { LOGGER.error("", e); } } } c = c.getSuperclass(); } sb.append("]"); } } return sb.toString(); }
Example 14
Source File: RestrictedFieldAccessingUtils.java From incubator-gobblin with Apache License 2.0 | 5 votes |
/** * Getting field defined in containingObj which was not publicly-accessible, using java-reflection. */ public static Object getRestrictedFieldByReflection(Object containingObj, String fieldName, Class clazz) throws NoSuchFieldException, IllegalAccessException { Field field = clazz.getDeclaredField(fieldName); field.setAccessible(true); return field.get(containingObj); }
Example 15
Source File: WebappClassLoaderBase.java From Tomcat7.0.67 with Apache License 2.0 | 4 votes |
private void checkThreadLocalsForLeaks() { Thread[] threads = getThreads(); try { // Make the fields in the Thread class that store ThreadLocals // accessible Field threadLocalsField = Thread.class.getDeclaredField("threadLocals"); threadLocalsField.setAccessible(true); Field inheritableThreadLocalsField = Thread.class.getDeclaredField("inheritableThreadLocals"); inheritableThreadLocalsField.setAccessible(true); // Make the underlying array of ThreadLoad.ThreadLocalMap.Entry objects // accessible Class<?> tlmClass = Class.forName("java.lang.ThreadLocal$ThreadLocalMap"); Field tableField = tlmClass.getDeclaredField("table"); tableField.setAccessible(true); Method expungeStaleEntriesMethod = tlmClass.getDeclaredMethod("expungeStaleEntries"); expungeStaleEntriesMethod.setAccessible(true); for (int i = 0; i < threads.length; i++) { Object threadLocalMap; if (threads[i] != null) { // Clear the first map threadLocalMap = threadLocalsField.get(threads[i]); if (null != threadLocalMap){ expungeStaleEntriesMethod.invoke(threadLocalMap); checkThreadLocalMapForLeaks(threadLocalMap, tableField); } // Clear the second map threadLocalMap =inheritableThreadLocalsField.get(threads[i]); if (null != threadLocalMap){ expungeStaleEntriesMethod.invoke(threadLocalMap); checkThreadLocalMapForLeaks(threadLocalMap, tableField); } } } } catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.warn(sm.getString( "webappClassLoader.checkThreadLocalsForLeaksFail", getContextName()), t); } }
Example 16
Source File: WebappClassLoaderBase.java From Tomcat7.0.67 with Apache License 2.0 | 4 votes |
private void clearReferencesStopTimerThread(Thread thread) { // Need to get references to: // in Sun/Oracle JDK: // - newTasksMayBeScheduled field (in java.util.TimerThread) // - queue field // - queue.clear() // in IBM JDK, Apache Harmony: // - cancel() method (in java.util.Timer$TimerImpl) try { try { Field newTasksMayBeScheduledField = thread.getClass().getDeclaredField("newTasksMayBeScheduled"); newTasksMayBeScheduledField.setAccessible(true); Field queueField = thread.getClass().getDeclaredField("queue"); queueField.setAccessible(true); Object queue = queueField.get(thread); Method clearMethod = queue.getClass().getDeclaredMethod("clear"); clearMethod.setAccessible(true); synchronized(queue) { newTasksMayBeScheduledField.setBoolean(thread, false); clearMethod.invoke(queue); queue.notify(); // In case queue was already empty. } }catch (NoSuchFieldException nfe){ Method cancelMethod = thread.getClass().getDeclaredMethod("cancel"); synchronized(thread) { cancelMethod.setAccessible(true); cancelMethod.invoke(thread); } } log.error(sm.getString("webappClassLoader.warnTimerThread", contextName, thread.getName())); } catch (Exception e) { // So many things to go wrong above... Throwable t = ExceptionUtils.unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(t); log.warn(sm.getString( "webappClassLoader.stopTimerThreadFail", thread.getName(), contextName), t); } }
Example 17
Source File: TypeNameTest.java From openjdk-8-source with GNU General Public License v2.0 | 4 votes |
public static void main(String[] args) throws Exception { TestMXBean testImpl = (TestMXBean) Proxy.newProxyInstance( TestMXBean.class.getClassLoader(), new Class<?>[] {TestMXBean.class}, nullIH); Object mxbean = new StandardMBean(testImpl, TestMXBean.class, true); MBeanServer mbs = MBeanServerFactory.newMBeanServer(); ObjectName name = new ObjectName("a:b=c"); mbs.registerMBean(mxbean, name); MBeanInfo mbi = mbs.getMBeanInfo(name); MBeanAttributeInfo[] mbais = mbi.getAttributes(); boolean sawTabular = false; for (MBeanAttributeInfo mbai : mbais) { String attrName = mbai.getName(); String attrTypeName = (String) mbai.getDescriptor().getFieldValue("originalType"); String fieldName = attrName + "Name"; Field nameField = TestMXBean.class.getField(fieldName); String expectedTypeName = (String) nameField.get(null); if (expectedTypeName.equals(attrTypeName)) { System.out.println("OK: " + attrName + ": " + attrTypeName); } else { fail("For attribute " + attrName + " expected type name \"" + expectedTypeName + "\", found type name \"" + attrTypeName + "\""); } if (mbai.getType().equals(TabularData.class.getName())) { sawTabular = true; TabularType tt = (TabularType) mbai.getDescriptor().getFieldValue("openType"); if (tt.getTypeName().equals(attrTypeName)) { System.out.println("OK: TabularType name for " + attrName); } else { fail("For attribute " + attrName + " expected TabularType " + "name \"" + attrTypeName + "\", found \"" + tt.getTypeName()); } } } if (!sawTabular) fail("Test bug: did not test TabularType name"); if (failure == null) System.out.println("TEST PASSED"); else throw new Exception("TEST FAILED: " + failure); }
Example 18
Source File: ObjectOutputStream.java From j2objc with Apache License 2.0 | 4 votes |
/** * Writes a collection of field values for the fields described by class * descriptor {@code classDesc} (an {@code ObjectStreamClass}). * This is the default mechanism, when emulated fields (an * {@code PutField}) are not used. Actual values to dump are fetched * directly from object {@code obj}. * * @param obj * Instance from which to fetch field values to dump. * @param classDesc * A class descriptor (an {@code ObjectStreamClass}) * defining which fields should be dumped. * * @throws IOException * If an IO exception happened when writing the field values. * * @see #writeObject(Object) */ private void writeFieldValues(Object obj, ObjectStreamClass classDesc) throws IOException { for (ObjectStreamField fieldDesc : classDesc.fields()) { try { Class<?> type = fieldDesc.getTypeInternal(); Field field = classDesc.getReflectionField(fieldDesc); if (field == null) { throw new InvalidClassException(classDesc.getName() + " doesn't have a field " + fieldDesc.getName() + " of type " + type); } if (type == byte.class) { output.writeByte(field.getByte(obj)); } else if (type == char.class) { output.writeChar(field.getChar(obj)); } else if (type == double.class) { output.writeDouble(field.getDouble(obj)); } else if (type == float.class) { output.writeFloat(field.getFloat(obj)); } else if (type == int.class) { output.writeInt(field.getInt(obj)); } else if (type == long.class) { output.writeLong(field.getLong(obj)); } else if (type == short.class) { output.writeShort(field.getShort(obj)); } else if (type == boolean.class) { output.writeBoolean(field.getBoolean(obj)); } else { // Reference types (including arrays). Object objField = field.get(obj); if (fieldDesc.isUnshared()) { writeUnshared(objField); } else { writeObject(objField); } } } catch (IllegalAccessException iae) { // ObjectStreamField should have called setAccessible(true). throw new AssertionError(iae); } catch (NoSuchFieldError nsf) { // The user defined serialPersistentFields but did not provide // the glue to transfer values in writeObject, so we ended up using // the default mechanism but failed to set the emulated field. throw new InvalidClassException(classDesc.getName()); } } }
Example 19
Source File: AbstractTCKTest.java From hottub with GNU General Public License v2.0 | 4 votes |
protected static void assertSerializedBySer(Object object, byte[] expectedBytes, byte[]... matches) throws Exception { String serClass = object.getClass().getPackage().getName() + ".Ser"; Class<?> serCls = Class.forName(serClass); Field field = serCls.getDeclaredField("serialVersionUID"); field.setAccessible(true); long serVer = (Long) field.get(null); ByteArrayOutputStream baos = new ByteArrayOutputStream(); try (ObjectOutputStream oos = new ObjectOutputStream(baos) ) { oos.writeObject(object); } byte[] bytes = baos.toByteArray(); ByteArrayInputStream bais = new ByteArrayInputStream(bytes); try (DataInputStream dis = new DataInputStream(bais)) { assertEquals(dis.readShort(), ObjectStreamConstants.STREAM_MAGIC); assertEquals(dis.readShort(), ObjectStreamConstants.STREAM_VERSION); assertEquals(dis.readByte(), ObjectStreamConstants.TC_OBJECT); assertEquals(dis.readByte(), ObjectStreamConstants.TC_CLASSDESC); assertEquals(dis.readUTF(), serClass); assertEquals(dis.readLong(), serVer); assertEquals(dis.readByte(), ObjectStreamConstants.SC_EXTERNALIZABLE | ObjectStreamConstants.SC_BLOCK_DATA); assertEquals(dis.readShort(), 0); // number of fields assertEquals(dis.readByte(), ObjectStreamConstants.TC_ENDBLOCKDATA); // end of classdesc assertEquals(dis.readByte(), ObjectStreamConstants.TC_NULL); // no superclasses if (expectedBytes.length < 256) { assertEquals(dis.readByte(), ObjectStreamConstants.TC_BLOCKDATA); assertEquals(dis.readUnsignedByte(), expectedBytes.length, "blockdata length incorrect"); } else { assertEquals(dis.readByte(), ObjectStreamConstants.TC_BLOCKDATALONG); assertEquals(dis.readInt(), expectedBytes.length, "blockdatalong length incorrect"); } byte[] input = new byte[expectedBytes.length]; dis.readFully(input); assertEquals(input, expectedBytes); if (matches.length > 0) { for (byte[] match : matches) { boolean matched = false; while (matched == false) { try { dis.mark(1000); byte[] possible = new byte[match.length]; dis.readFully(possible); assertEquals(possible, match); matched = true; } catch (AssertionError ex) { dis.reset(); dis.readByte(); // ignore } } } } else { assertEquals(dis.readByte(), ObjectStreamConstants.TC_ENDBLOCKDATA); // end of blockdata assertEquals(dis.read(), -1); } } }
Example 20
Source File: JsonUtils.java From Cangol-appcore with Apache License 2.0 | 4 votes |
public static <T> JSONObject toJSONObject(T obj, boolean useAnnotation,boolean excludeTransient) { if (obj == null) { return null; } if (List.class.isAssignableFrom(obj.getClass())) { return null; } final JSONObject json = new JSONObject(); final Field[] fields = obj.getClass().getDeclaredFields(); try { for (final Field field : fields) { field.setAccessible(true); if (field.isEnumConstant() || Modifier.isFinal(field.getModifiers())) { continue; } if(excludeTransient&&Modifier.isTransient(field.getModifiers())){ continue; } final String filedName = getFieldName(field, useAnnotation); if (!List.class.isAssignableFrom(field.getType())) { //非集合类型 if (isBaseClass(field.getType())) { json.put(filedName, field.get(obj)); } else { json.put(filedName, toJSONObject(field.get(obj), useAnnotation)); } } else { //集合类型 if (field.getGenericType() instanceof ParameterizedType) { final List<?> list = (List<?>) field.get(obj); final JSONArray jsonArray = new JSONArray(); if (list != null) { for (int i = 0; i < list.size(); i++) { if (isBaseClass(list.get(i).getClass())) { jsonArray.put(list.get(i)); } else { jsonArray.put(toJSONObject(list.get(i), useAnnotation)); } } } json.put(filedName, jsonArray); } else { Log.d(TAG, field.getName() + " require have generic"); } } } } catch (Exception e) { Log.d(TAG, e.getMessage()); } return json; }