Java Code Examples for java.lang.reflect.Field.get()

The following are Jave code examples for showing how to use get() of the java.lang.reflect.Field class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: Equella   File: BeanPropertySerialiser.java   View Source Code Vote up 7 votes
@Override
public void query(Object object, Field field, Collection<String> queries)
	throws IllegalAccessException, InstantiationException
{
	Class<?> type = field.getType();
	if( ConfigurationProperties.class.isAssignableFrom(type) )
	{
		ConfigurationProperties fobject = (ConfigurationProperties) field.get(object);
		if( fobject == null )
		{
			fobject = (ConfigurationProperties) type.newInstance();
			field.set(object, fobject);
		}
		queries.addAll(PropertyBeanFactory.getSelect(fobject));
	}
}
 
Example 2
Project: RLibrary   File: Reflect.java   View Source Code Vote up 6 votes
/**
 * 通过反射, 获取obj对象的 指定成员变量的值
 */
public static Object getFieldValue(Object obj, String fieldName) {
    if (obj == null || TextUtils.isEmpty(fieldName)) {
        return null;
    }

    Class<?> clazz = obj.getClass();
    while (clazz != Object.class) {
        try {
            Field field = clazz.getDeclaredField(fieldName);
            field.setAccessible(true);
            return field.get(obj);
        } catch (Exception e) {
            L.e("错误:" + e.getMessage());
        }
        clazz = clazz.getSuperclass();
    }
    return null;
}
 
Example 3
Project: letv   File: BasicActivity.java   View Source Code Vote up 6 votes
public void showPopupDialog(Dialog dialog) {
    try {
        Field field = dialog.getClass().getDeclaredField("mAlert");
        field.setAccessible(true);
        Object obj = field.get(dialog);
        field = obj.getClass().getDeclaredField("mHandler");
        field.setAccessible(true);
        field.set(obj, new ButtonHandler(dialog));
    } catch (SecurityException e) {
        LOG.e(TAG, "set button handler failed(SecurityException)", e);
    } catch (NoSuchFieldException e2) {
        LOG.e(TAG, "set button handler failed(NoSuchFieldException)", e2);
    } catch (IllegalArgumentException e3) {
        LOG.e(TAG, "set button handler failed(IllegalArgumentException)", e3);
    } catch (IllegalAccessException e4) {
        LOG.e(TAG, "set button handler failed(IllegalAccessException)", e4);
    } catch (Throwable t) {
        LOG.e(TAG, "set button handler failed(Throwable)", t);
    }
    dialog.show();
}
 
Example 4
Project: letv   File: ResourceUtil.java   View Source Code Vote up 6 votes
private static Object getResourceId(Context context, String name, String type) {
    try {
        for (Class childClass : Class.forName(context.getPackageName() + ".R").getClasses()) {
            if (childClass.getSimpleName().equals(type)) {
                for (Field field : childClass.getFields()) {
                    if (field.getName().equals(name)) {
                        return field.get(null);
                    }
                }
                continue;
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}
 
Example 5
Project: Wurst-MC-1.12   File: ModManager.java   View Source Code Vote up 6 votes
public ModManager()
{
	try
	{
		for(Field field : ModManager.class.getFields())
			if(field.getName().endsWith("Mod"))
			{
				Mod mod = (Mod)field.get(this);
				mods.put(mod.getName(), mod);
				mod.initSettings();
			}
		
	}catch(Exception e)
	{
		throw new ReportedException(
			CrashReport.makeCrashReport(e, "Initializing Wurst mods"));
	}
}
 
Example 6
Project: GitHub   File: TinkerLoadLibrary.java   View Source Code Vote up 6 votes
private static void install(ClassLoader classLoader, File folder)  throws Throwable {
    Field pathListField = ShareReflectUtil.findField(classLoader, "pathList");
    Object dexPathList = pathListField.get(classLoader);

    Field nativeLibraryDirectories = ShareReflectUtil.findField(dexPathList, "nativeLibraryDirectories");

    List<File> libDirs = (List<File>) nativeLibraryDirectories.get(dexPathList);
    libDirs.add(0, folder);
    Field systemNativeLibraryDirectories =
            ShareReflectUtil.findField(dexPathList, "systemNativeLibraryDirectories");
    List<File> systemLibDirs = (List<File>) systemNativeLibraryDirectories.get(dexPathList);
    Method makePathElements =
            ShareReflectUtil.findMethod(dexPathList, "makePathElements", List.class);
    libDirs.addAll(systemLibDirs);
    Object[] elements = (Object[]) makePathElements.
            invoke(dexPathList, libDirs);
    Field nativeLibraryPathElements = ShareReflectUtil.findField(dexPathList, "nativeLibraryPathElements");
    nativeLibraryPathElements.setAccessible(true);
    nativeLibraryPathElements.set(dexPathList, elements);
}
 
Example 7
Project: android-dev-challenge   File: TestUtilities.java   View Source Code Vote up 5 votes
static Integer getStaticIntegerField(Class clazz, String variableName)
        throws NoSuchFieldException, IllegalAccessException {
    Field intField = clazz.getDeclaredField(variableName);
    intField.setAccessible(true);
    Integer value = (Integer) intField.get(null);
    return value;
}
 
Example 8
Project: monarch   File: DomainObject.java   View Source Code Vote up 5 votes
public Object get(String varName) throws Exception {
  Field f;
  try {
    f = this.getClass().getDeclaredField(varName);
  } catch (NoSuchFieldException fex) {
    f = this.getClass().getSuperclass().getDeclaredField(varName);
  }
  Object o = f.get(this);
  return o;
}
 
Example 9
Project: FuzzDroid   File: Hooker.java   View Source Code Vote up 5 votes
private static Object retrieveOldFieldValue(String className, String fieldName) {
 	try {
  	Class<?> tmp  = Class.forName(className);	
Field field = tmp.getField(fieldName);
field.setAccessible(true);
return field.get(Class.forName(className));
 	}catch(Exception ex) {
 		ex.printStackTrace();
 		return null;
 	}
 }
 
Example 10
Project: springreplugin   File: PluginAppCompatActivity.java   View Source Code Vote up 5 votes
/**
 * 这里的做法是支持Fragment中调用startActivityForResult特性
 * <p>
 * 由于卫士的插件需要hook住XXX-Activity的startActivity和startActivityForResult接口
 * 但早期版本的support-v4在startActivityFromFragment中直接调用了super.startActivityForResult, 因此这里还需要hook住这个点
 * 但新版的support-v4中Fragment最终的调用链还是会走到本XXX-Activity的startActivityForResult接口,因此不需要适配startActivityFromFragment(Fragment fragment, Intent intent, int requestCode, @Nullable Bundle options)接口
 *
 * @param fragment
 * @param intent
 * @param requestCode
 */
@Override
public void startActivityFromFragment(Fragment fragment, Intent intent, int requestCode) {
    if (requestCode == -1) {
        startActivityForResult(intent, -1);
    } else if ((requestCode & -65536) != 0) {
        throw new IllegalArgumentException("Can only use lower 16 bits for requestCode");
    } else {
        int newRequestCode = -1;
        try {
            Field f = Fragment.class.getDeclaredField("mIndex");
            boolean acc = f.isAccessible();
            if (!acc) {
                f.setAccessible(true);
            }
            Object o = f.get(fragment);
            if (!acc) {
                f.setAccessible(acc);
            }
            int index = (Integer) o;
            newRequestCode = ((index + 1) << 16) + (requestCode & '\uffff');
        } catch (Throwable e) {
            // Do Noting
        }
        startActivityForResult(intent, newRequestCode);
    }
}
 
Example 11
Project: wisp   File: UnitTestDependencyInjectionTestExecutionListener.java   View Source Code Vote up 5 votes
@Override
protected void injectDependencies(TestContext testContext) throws Exception {
    super.injectDependencies(testContext);
    /**
     * 获取测试类 & fields
     */
    Object bean = testContext.getTestInstance();
    List<Field> fields = getDeclaredFields(bean);
    if (CollectionUtils.isEmpty(fields)) {
        return;
    }
    /**
     * 如果测试类中, 被测试对象含有mockito的@InjectMocks注解,且 被测试对象被事务拦截器拦截 则 用原始对象代替
     */
    for (Field field : fields) {
        InjectMocks injectMocks = field.getAnnotation(InjectMocks.class);
        if (injectMocks == null) {
            continue;
        }
        field.setAccessible(true);
        Object proxy = field.get(bean);
        if (AopUtils.isAopProxy(proxy)) {
            // 替换对象
            Object target = ((Advised) proxy).getTargetSource().getTarget();
            field.set(bean, target);
        }
    }
}
 
Example 12
Project: RLibrary   File: RLinearLayoutManager.java   View Source Code Vote up 5 votes
void ensureChildHelper() {
    try {
        if (mInnerChildHelper == null) {
            mInnerChildHelper = mChildHelperField.get(mLayoutManager);
            if (mInnerChildHelper == null) return;

            Class<?> helperClz = mInnerChildHelper.getClass();
            mHideMethod = helperClz.getDeclaredMethod("hide", View.class);
            mHideMethod.setAccessible(true);
            mFindHiddenNonRemovedViewMethod = helperClz.getDeclaredMethod("findHiddenNonRemovedView", int.class/*, int.class*/);
            mFindHiddenNonRemovedViewMethod.setAccessible(true);
            mIsHideMethod = helperClz.getDeclaredMethod("isHidden", View.class);
            mIsHideMethod.setAccessible(true);

            Field bucketField = helperClz.getDeclaredField("mBucket");
            bucketField.setAccessible(true);

            mInnerBucket = bucketField.get(mInnerChildHelper);
            mClearMethod = mInnerBucket.getClass().getDeclaredMethod("clear", int.class);
            mClearMethod.setAccessible(true);

            mHiddenViewField = helperClz.getDeclaredField("mHiddenViews");
            mHiddenViewField.setAccessible(true);
            mInnerHiddenView = (List) mHiddenViewField.get(mInnerChildHelper);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

}
 
Example 13
Project: marathon-auth-plugin   File: AuthUtil.java   View Source Code Vote up 5 votes
public static Object getFieldVal(Object o,String fieldName){
try {
	Field field = getDeclaredField(o, fieldName);
	field.setAccessible(true); 
       return field.get(o); 
} catch (Exception ex) {
	log.error(ex.getMessage(), ex);
}
return null;
  }
 
Example 14
Project: jdk8u-jdk   File: AbstractTCKTest.java   View Source Code Vote up 5 votes
/**
 * Verify the class cannot be deserialized from a handcoded stream.
 * Fail if the deserialization does <em>not</em> throw an Exception.
 * @param serClass the class to embed in the handcoded stream
 * @throws Exception if an unexpected condition occurs
 */
protected static void assertNotSerializable(Class<?> serClass) throws Exception {
    Field field = serClass.getDeclaredField("serialVersionUID");
    field.setAccessible(true);
    long serVer = (Long) field.get(null);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try (DataOutputStream out = new DataOutputStream(baos)) {
        out.writeShort(ObjectStreamConstants.STREAM_MAGIC);
        out.writeShort(ObjectStreamConstants.STREAM_VERSION);
        out.writeByte(ObjectStreamConstants.TC_OBJECT);
        out.writeByte(ObjectStreamConstants.TC_CLASSDESC);
        out.writeUTF(serClass.getName());
        out.writeLong(serVer);
        out.writeByte(ObjectStreamConstants.SC_SERIALIZABLE);   // Flags ObjectStreamConstants
        out.writeShort(0);  // number of fields
        out.writeByte(ObjectStreamConstants.TC_ENDBLOCKDATA);
        out.writeByte(ObjectStreamConstants.TC_NULL);  // no superclasses
    }

    byte[] bytes = baos.toByteArray();

    try (ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
        ObjectInputStream in = new ObjectInputStream(bis)) {
        Object o = in.readObject();
    } catch (Exception ioe) {
        // Expected exception
        return;
    }
    fail("Class should not be deserializable " + serClass.getName());
}
 
Example 15
Project: codelens-eclipse   File: LineNumberChangeRulerColumnPatch.java   View Source Code Vote up 5 votes
private static <T> T getValue(String name, Object instance) {
	try {
		Field f = LineNumberChangeRulerColumn.class.getDeclaredField(name);
		f.setAccessible(true);
		return (T) f.get(instance);
	} catch (Exception e) {
		e.printStackTrace();
		return null;
	}
}
 
Example 16
Project: DevoxxFr2017   File: Ex8Service.java   View Source Code Vote up 5 votes
private ManagementRegistryService getManagementRegistryService(CacheManager cacheManager) {
  try {
    org.ehcache.CacheManager unwrap = cacheManager.unwrap(org.ehcache.CacheManager.class);
    Field serviceLocatorField = org.ehcache.core.EhcacheManager.class.getDeclaredField("serviceLocator");
    serviceLocatorField.setAccessible(true);
    ServiceLocator result = (ServiceLocator)serviceLocatorField.get(unwrap);
    return result.getService(ManagementRegistryService.class);
  } catch (Exception e) {
    throw new RuntimeException(e);
  }
}
 
Example 17
Project: hibernateMaster   File: DomainUtil.java   View Source Code Vote up 5 votes
private static <T> Object getFieldValue(T target, Field f) throws IllegalAccessException {
	Object field = ReflectUtil.getFieldValueByGetter(target, f.getName());
	if (field == null) {
		field = f.get(target);
	}
	return field;
}
 
Example 18
Project: openjdk-jdk10   File: MXBeanTest.java   View Source Code Vote up 4 votes
private static <T> void testInterface(Class<T> c, boolean nullTest)
        throws Exception {

    System.out.println("Testing " + c.getName() +
                       (nullTest ? " for null values" : "") + "...");

    MBeanServer mbs = MBeanServerFactory.newMBeanServer();

    JMXServiceURL url = new JMXServiceURL("rmi", null, 0);
    JMXConnectorServer cs =
        JMXConnectorServerFactory.newJMXConnectorServer(url, null, mbs);
    cs.start();
    JMXServiceURL addr = cs.getAddress();
    JMXConnector cc = JMXConnectorFactory.connect(addr);
    MBeanServerConnection mbsc = cc.getMBeanServerConnection();

    NamedMXBeans namedMXBeans = new NamedMXBeans(mbsc);
    InvocationHandler ih =
        nullTest ? new MXBeanNullImplInvocationHandler(c, namedMXBeans) :
                   new MXBeanImplInvocationHandler(c, namedMXBeans);
    T impl = c.cast(Proxy.newProxyInstance(c.getClassLoader(),
                                           new Class[] {c},
                                           ih));
    ObjectName on = new ObjectName("test:type=" + c.getName());
    mbs.registerMBean(impl, on);

    System.out.println("Register any MXBeans...");

    Field[] fields = c.getFields();
    for (Field field : fields) {
        String n = field.getName();
        if (n.endsWith("ObjectName")) {
            String objectNameString = (String) field.get(null);
            String base = n.substring(0, n.length() - 10);
            Field f = c.getField(base);
            Object mxbean = f.get(null);
            ObjectName objectName =
                ObjectName.getInstance(objectNameString);
            mbs.registerMBean(mxbean, objectName);
            namedMXBeans.put(objectName, mxbean);
        }
    }

    try {
        testInterface(c, mbsc, on, namedMXBeans, nullTest);
    } finally {
        try {
            cc.close();
        } finally {
            cs.stop();
        }
    }
}
 
Example 19
Project: openjdk-jdk10   File: DGCAckFailure.java   View Source Code Vote up 4 votes
public static void main(String[] args) throws Exception {

        System.setProperty("sun.rmi.dgc.ackTimeout",
                Long.toString(ACK_TIMEOUT));

        /*
         * Set a socket factory that has a hook for shutting down all client
         * output (writes from client-created sockets and new connection
         * attempts).  We then use this hook right before a remote stub gets
         * deserialized, so that the client will not be able to send a DGC
         * dirty call, or a DGC acknowledgment.  Without the DGC ack, we
         * hope that the RMI runtime will still eventually allow the remote
         * object to be garbage collected.
         */
        RMISocketFactory.setSocketFactory(new TestSF());
        System.err.println("test socket factory set");

        Remote impl = new DGCAckFailure();
        ReferenceQueue refQueue = new ReferenceQueue();
        Reference weakRef = new WeakReference(impl, refQueue);
        ReturnRemote stub =
            (ReturnRemote) UnicastRemoteObject.exportObject(impl);
        System.err.println("remote object exported; stub = " + stub);

        try {
            Object wrappedStub = stub.returnRemote();
            System.err.println("invocation returned: " + wrappedStub);

            impl = null;
            stub = null;        // in case 4114579 ever gets fixed
            System.err.println("strong references to impl cleared");

            System.err.println("waiting for weak reference notification:");
            Reference ref = null;
            for (int i = 0; i < 6; i++) {
                System.gc();
                ref = refQueue.remove(TIMEOUT / 5);
                if (ref != null) {
                    break;
                }
            }
            if (ref != weakRef) {
                throw new RuntimeException("TEST FAILED: " +
                    "timed out, remote object not garbage collected");
            }

            // 8046339
            // All DGCAckHandlers must be properly released after timeout
            Thread.sleep(ACK_TIMEOUT + 100);
            try {
                Field field =
                        DGCAckHandler.class.getDeclaredField("idTable");
                field.setAccessible(true);
                Object obj = field.get(null);
                Map<?,?> idTable = (Map<?,?>)obj;

                if (!idTable.isEmpty()) {
                    throw new RuntimeException("TEST FAILED: " +
                            "DGCAckHandler.idTable isn't empty");
                }
            } catch (ReflectiveOperationException roe) {
                throw new RuntimeException(roe);
            }

            System.err.println("TEST PASSED");

        } finally {
            try {
                UnicastRemoteObject.unexportObject((Remote) weakRef.get(),
                                                   true);
            } catch (Exception e) {
            }
        }
    }
 
Example 20
Project: jdk8u-jdk   File: bug6938813.java   View Source Code Vote up 3 votes
private static Object getParserDelegator_DTD_KEY() throws Exception {
    Field field = ParserDelegator.class.getDeclaredField("DTD_KEY");

    field.setAccessible(true);

    return field.get(null);
}