List of usage examples for java.lang Class getDeclaredField
@CallerSensitive public Field getDeclaredField(String name) throws NoSuchFieldException, SecurityException
From source file:Main.java
public static Service createService(Context context, ServiceInfo serviceInfo) throws Exception { IBinder token = new Binder(); Class<?> createServiceDataClass = Class.forName("android.app.ActivityThread$CreateServiceData"); Constructor<?> constructor = createServiceDataClass.getDeclaredConstructor(); constructor.setAccessible(true);/*from w w w . j av a 2s . c om*/ Object createServiceData = constructor.newInstance(); Field tokenField = createServiceDataClass.getDeclaredField("token"); tokenField.setAccessible(true); tokenField.set(createServiceData, token); serviceInfo.applicationInfo.packageName = context.getPackageName(); Field infoField = createServiceDataClass.getDeclaredField("info"); infoField.setAccessible(true); infoField.set(createServiceData, serviceInfo); Class<?> compatibilityClass = Class.forName("android.content.res.CompatibilityInfo"); Field defaultCompatibilityField = compatibilityClass.getDeclaredField("DEFAULT_COMPATIBILITY_INFO"); defaultCompatibilityField.setAccessible(true); Object defaultCompatibility = defaultCompatibilityField.get(null); defaultCompatibilityField.set(createServiceData, defaultCompatibility); Class<?> activityThreadClass = Class.forName("android.app.ActivityThread"); Method currentActivityThreadMethod = activityThreadClass.getDeclaredMethod("currentActivityThread"); Object currentActivityThread = currentActivityThreadMethod.invoke(null); Method handleCreateServiceMethod = activityThreadClass.getDeclaredMethod("handleCreateService", createServiceDataClass); handleCreateServiceMethod.setAccessible(true); handleCreateServiceMethod.invoke(currentActivityThread, createServiceData); Field mServicesField = activityThreadClass.getDeclaredField("mServices"); mServicesField.setAccessible(true); Map mServices = (Map) mServicesField.get(currentActivityThread); Service service = (Service) mServices.get(token); mServices.remove(token); return service; }
From source file:com.comphenix.protocol.injector.EntityUtilities.java
/** * Retrieve entity from a ID, even it it's newly created. * @return The associated entity.//from w w w. ja v a2s . co m * @throws FieldAccessException Reflection error. */ public static Entity getEntityFromID(World world, int entityID) throws FieldAccessException { try { Object trackerEntry = getEntityTrackerEntry(world, entityID); Object tracker = null; // Handle NULL cases if (trackerEntry != null) { if (trackerField == null) { try { Class<?> entryClass = MinecraftReflection.getMinecraftClass("EntityTrackerEntry"); trackerField = entryClass.getDeclaredField("tracker"); } catch (NoSuchFieldException e) { // Assume it's the first entity field then trackerField = FuzzyReflection.fromObject(trackerEntry, true).getFieldByType("tracker", MinecraftReflection.getEntityClass()); } } tracker = FieldUtils.readField(trackerField, trackerEntry, true); } // If the tracker is NULL, we'll just assume this entity doesn't exist if (tracker != null) return (Entity) MinecraftReflection.getBukkitEntity(tracker); else return null; } catch (Exception e) { throw new FieldAccessException("Cannot find entity from ID " + entityID + ".", e); } }
From source file:com.dubsar_dictionary.Dubsar.FAQActivity.java
/** * Set Proxy for Android 4.1 and above./*from w ww. jav a 2 s. c o m*/ */ @SuppressWarnings("all") private static boolean setProxyJBPlus(WebView webview, String host, int port) { Log.d(LOG_TAG, "Setting proxy with >= 4.1 API."); try { Class wvcClass = Class.forName("android.webkit.WebViewClassic"); Class wvParams[] = new Class[1]; wvParams[0] = Class.forName("android.webkit.WebView"); Method fromWebView = wvcClass.getDeclaredMethod("fromWebView", wvParams); Object webViewClassic = fromWebView.invoke(null, webview); Class wv = Class.forName("android.webkit.WebViewClassic"); Field mWebViewCoreField = wv.getDeclaredField("mWebViewCore"); Object mWebViewCoreFieldInstance = getFieldValueSafely(mWebViewCoreField, webViewClassic); Class wvc = Class.forName("android.webkit.WebViewCore"); Field mBrowserFrameField = wvc.getDeclaredField("mBrowserFrame"); Object mBrowserFrame = getFieldValueSafely(mBrowserFrameField, mWebViewCoreFieldInstance); Class bf = Class.forName("android.webkit.BrowserFrame"); Field sJavaBridgeField = bf.getDeclaredField("sJavaBridge"); Object sJavaBridge = getFieldValueSafely(sJavaBridgeField, mBrowserFrame); Class ppclass = Class.forName("android.net.ProxyProperties"); Class pparams[] = new Class[3]; pparams[0] = String.class; pparams[1] = int.class; pparams[2] = String.class; Constructor ppcont = ppclass.getConstructor(pparams); Class jwcjb = Class.forName("android.webkit.JWebCoreJavaBridge"); Class params[] = new Class[1]; params[0] = Class.forName("android.net.ProxyProperties"); Method updateProxyInstance = jwcjb.getDeclaredMethod("updateProxy", params); updateProxyInstance.invoke(sJavaBridge, ppcont.newInstance(host, port, null)); } catch (Exception ex) { Log.e(LOG_TAG, "Setting proxy with >= 4.1 API failed with error: " + ex.getMessage()); return false; } Log.d(LOG_TAG, "Setting proxy with >= 4.1 API successful!"); return true; }
From source file:com.spotify.helios.client.DefaultHttpConnector.java
private static void setRequestMethod(final HttpURLConnection connection, final String method, final boolean isHttps) { // Nasty workaround for ancient HttpURLConnection only supporting few methods final Class<?> httpURLConnectionClass = connection.getClass(); try {/*ww w . j av a2s . co m*/ Field methodField; HttpURLConnection delegate; if (isHttps) { final Field delegateField = httpURLConnectionClass.getDeclaredField("delegate"); delegateField.setAccessible(true); delegate = (HttpURLConnection) delegateField.get(connection); methodField = delegate.getClass().getSuperclass().getSuperclass().getSuperclass() .getDeclaredField("method"); } else { delegate = connection; methodField = httpURLConnectionClass.getSuperclass().getDeclaredField("method"); } methodField.setAccessible(true); methodField.set(delegate, method); } catch (NoSuchFieldException | IllegalAccessException e) { throw Throwables.propagate(e); } }
From source file:Main.java
public static <T> T getPrivateConstantField(Class<?> outerClass, String innerClassName, String fieldname, Class<T> returnType) throws Exception { // Get all inner classes Class<?> innerClasses[] = outerClass.getDeclaredClasses(); // find the inner class that matches the order Class<?> innerClass = null; for (int index = 0; index < innerClasses.length; index++) { if (innerClassName.equals(innerClasses[index].getSimpleName())) { innerClass = innerClasses[index]; }/* www . j a v a2s.com*/ } T returnValue = null; if (innerClass != null) { Field field; field = innerClass.getDeclaredField(fieldname); field.setAccessible(true); returnValue = (T) field.get(innerClass); } return returnValue; }
From source file:com.psiphon3.psiphonlibrary.WebViewProxySettings.java
@TargetApi(Build.VERSION_CODES.KITKAT) @SuppressWarnings("rawtypes") private static boolean setWebkitProxyKitKat(Context appContext, String host, int port) { System.setProperty("http.proxyHost", host); System.setProperty("http.proxyPort", port + ""); System.setProperty("https.proxyHost", host); System.setProperty("https.proxyPort", port + ""); try {//www .j a v a 2 s.c o m Class applicationClass = Class.forName("android.app.Application"); Field loadedApkField = applicationClass.getDeclaredField("mLoadedApk"); loadedApkField.setAccessible(true); Object loadedApk = loadedApkField.get(appContext); Class loadedApkClass = Class.forName("android.app.LoadedApk"); Field receiversField = loadedApkClass.getDeclaredField("mReceivers"); receiversField.setAccessible(true); ArrayMap receivers = (ArrayMap) receiversField.get(loadedApk); for (Object receiverMap : receivers.values()) { for (Object receiver : ((ArrayMap) receiverMap).keySet()) { Class receiverClass = receiver.getClass(); if (receiverClass.getName().contains("ProxyChangeListener")) { Method onReceiveMethod = receiverClass.getDeclaredMethod("onReceive", Context.class, Intent.class); Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION); final String CLASS_NAME = "android.net.ProxyProperties"; Class proxyPropertiesClass = Class.forName(CLASS_NAME); Constructor constructor = proxyPropertiesClass.getConstructor(String.class, Integer.TYPE, String.class); constructor.setAccessible(true); Object proxyProperties = constructor.newInstance(host, port, null); intent.putExtra("proxy", (Parcelable) proxyProperties); onReceiveMethod.invoke(receiver, appContext, intent); } } } return true; } catch (ClassNotFoundException e) { MyLog.d("Exception setting WebKit proxy on KitKat through ProxyChangeListener: " + e.toString()); } catch (NoSuchFieldException e) { MyLog.d("Exception setting WebKit proxy on KitKat through ProxyChangeListener: " + e.toString()); } catch (IllegalAccessException e) { MyLog.d("Exception setting WebKit proxy on KitKat through ProxyChangeListener: " + e.toString()); } catch (IllegalArgumentException e) { MyLog.d("Exception setting WebKit proxy on KitKat through ProxyChangeListener: " + e.toString()); } catch (NoSuchMethodException e) { MyLog.d("Exception setting WebKit proxy on KitKat through ProxyChangeListener: " + e.toString()); } catch (InvocationTargetException e) { MyLog.d("Exception setting WebKit proxy on KitKat through ProxyChangeListener: " + e.toString()); } catch (InstantiationException e) { MyLog.d("Exception setting WebKit proxy on KitKat through ProxyChangeListener: " + e.toString()); } return false; }
From source file:com.feilong.core.lang.reflect.FieldUtilTemp.java
/** * {@link Field},?? Class?./* ww w . ja v a2 s . c o m*/ * * @param klass * the klass * @param fieldName * ?? * @return <code>klass</code> null, {@link NullPointerException}<br> * <code>fieldName</code> null, {@link NullPointerException}<br> * <code>fieldName</code> blank, {@link IllegalArgumentException}<br> * @see java.lang.Class#getDeclaredField(String) * @see org.apache.commons.lang3.reflect.FieldUtils#getDeclaredField(Class, String, boolean) */ public static Field getDeclaredField(Class<?> klass, String fieldName) { Validate.notNull(klass, "klass can't be null!"); Validate.notEmpty(fieldName, "fieldName can't be null/empty!"); try { return klass.getDeclaredField(fieldName); } catch (Exception e) { throw new ReflectException(e); } }
From source file:com.hurence.logisland.util.string.StringUtilsTest.java
/** * Sets an environment variable FOR THE CURRENT RUN OF THE JVM * Does not actually modify the system's environment variables, * but rather only the copy of the variables that java has taken, * and hence should only be used for testing purposes! * @param key The Name of the variable to set * @param value The value of the variable to set *//*w ww . ja v a2 s .c om*/ @SuppressWarnings("unchecked") public static <K, V> void setEnv(final String key, final String value) throws InvocationTargetException { try { /// we obtain the actual environment final Class<?> processEnvironmentClass = Class.forName("java.lang.ProcessEnvironment"); final Field theEnvironmentField = processEnvironmentClass.getDeclaredField("theEnvironment"); final boolean environmentAccessibility = theEnvironmentField.isAccessible(); theEnvironmentField.setAccessible(true); final Map<K, V> env = (Map<K, V>) theEnvironmentField.get(null); if (SystemUtils.IS_OS_WINDOWS) { // This is all that is needed on windows running java jdk 1.8.0_92 if (value == null) { env.remove(key); } else { env.put((K) key, (V) value); } } else { // This is triggered to work on openjdk 1.8.0_91 // The ProcessEnvironment$Variable is the key of the map final Class<K> variableClass = (Class<K>) Class.forName("java.lang.ProcessEnvironment$Variable"); final Method convertToVariable = variableClass.getMethod("valueOf", String.class); final boolean conversionVariableAccessibility = convertToVariable.isAccessible(); convertToVariable.setAccessible(true); // The ProcessEnvironment$Value is the value fo the map final Class<V> valueClass = (Class<V>) Class.forName("java.lang.ProcessEnvironment$Value"); final Method convertToValue = valueClass.getMethod("valueOf", String.class); final boolean conversionValueAccessibility = convertToValue.isAccessible(); convertToValue.setAccessible(true); if (value == null) { env.remove(convertToVariable.invoke(null, key)); } else { // we place the new value inside the map after conversion so as to // avoid class cast exceptions when rerunning this code env.put((K) convertToVariable.invoke(null, key), (V) convertToValue.invoke(null, value)); // reset accessibility to what they were convertToValue.setAccessible(conversionValueAccessibility); convertToVariable.setAccessible(conversionVariableAccessibility); } } // reset environment accessibility theEnvironmentField.setAccessible(environmentAccessibility); // we apply the same to the case insensitive environment final Field theCaseInsensitiveEnvironmentField = processEnvironmentClass .getDeclaredField("theCaseInsensitiveEnvironment"); final boolean insensitiveAccessibility = theCaseInsensitiveEnvironmentField.isAccessible(); theCaseInsensitiveEnvironmentField.setAccessible(true); // Not entirely sure if this needs to be casted to ProcessEnvironment$Variable and $Value as well final Map<String, String> cienv = (Map<String, String>) theCaseInsensitiveEnvironmentField.get(null); if (value == null) { // remove if null cienv.remove(key); } else { cienv.put(key, value); } theCaseInsensitiveEnvironmentField.setAccessible(insensitiveAccessibility); } catch (final ClassNotFoundException | NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { throw new IllegalStateException("Failed setting environment variable <" + key + "> to <" + value + ">", e); } catch (final NoSuchFieldException e) { // we could not find theEnvironment final Map<String, String> env = System.getenv(); Stream.of(Collections.class.getDeclaredClasses()) // obtain the declared classes of type $UnmodifiableMap .filter(c1 -> "java.util.Collections$UnmodifiableMap".equals(c1.getName())).map(c1 -> { try { return c1.getDeclaredField("m"); } catch (final NoSuchFieldException e1) { throw new IllegalStateException("Failed setting environment variable <" + key + "> to <" + value + "> when locating in-class memory map of environment", e1); } }).forEach(field -> { try { final boolean fieldAccessibility = field.isAccessible(); field.setAccessible(true); // we obtain the environment final Map<String, String> map = (Map<String, String>) field.get(env); if (value == null) { // remove if null map.remove(key); } else { map.put(key, value); } // reset accessibility field.setAccessible(fieldAccessibility); } catch (final ConcurrentModificationException e1) { // This may happen if we keep backups of the environment before calling this method // as the map that we kept as a backup may be picked up inside this block. // So we simply skip this attempt and continue adjusting the other maps // To avoid this one should always keep individual keys/value backups not the entire map System.out.println("Attempted to modify source map: " + field.getDeclaringClass() + "#" + field.getName() + e1); } catch (final IllegalAccessException e1) { throw new IllegalStateException("Failed setting environment variable <" + key + "> to <" + value + ">. Unable to access field!", e1); } }); } System.out.println( "Set environment variable <" + key + "> to <" + value + ">. Sanity Check: " + System.getenv(key)); }
From source file:me.totalfreedom.totalfreedommod.util.FUtil.java
@SuppressWarnings("unchecked") public static <T> T getField(Object from, String name) { Class<?> checkClass = from.getClass(); do {//from w w w . j a v a2 s .c om try { Field field = checkClass.getDeclaredField(name); field.setAccessible(true); return (T) field.get(from); } catch (NoSuchFieldException | IllegalAccessException ex) { } } while (checkClass.getSuperclass() != Object.class && ((checkClass = checkClass.getSuperclass()) != null)); return null; }
From source file:Main.java
/** * Determines whether notifications are enabled for the app represented by |context|. * Notifications may be disabled because either the user, or a management tool, has explicitly * disallowed the Chrome App to display notifications. * * This check requires Android KitKat or later. Earlier versions will return an INDETERMINABLE * status. When an exception occurs, an EXCEPTION status will be returned instead. * * @param context The context to check of whether it can show notifications. * @return One of the APP_NOTIFICATION_STATUS_* constants defined in this class. *///from www . j a v a 2s . c om @TargetApi(Build.VERSION_CODES.KITKAT) static int determineAppNotificationStatus(Context context) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) { return APP_NOTIFICATIONS_STATUS_UNDETERMINABLE; } final String packageName = context.getPackageName(); final int uid = context.getApplicationInfo().uid; final AppOpsManager appOpsManager = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE); try { Class appOpsManagerClass = Class.forName(AppOpsManager.class.getName()); @SuppressWarnings("unchecked") final Method checkOpNoThrowMethod = appOpsManagerClass.getMethod(CHECK_OP_NO_THROW, Integer.TYPE, Integer.TYPE, String.class); final Field opPostNotificationField = appOpsManagerClass.getDeclaredField(OP_POST_NOTIFICATION); int value = (int) opPostNotificationField.get(Integer.class); int status = (int) checkOpNoThrowMethod.invoke(appOpsManager, value, uid, packageName); return status == AppOpsManager.MODE_ALLOWED ? APP_NOTIFICATIONS_STATUS_ENABLED : APP_NOTIFICATIONS_STATUS_DISABLED; } catch (RuntimeException e) { } catch (Exception e) { // Silently fail here, since this is just collecting statistics. The histogram includes // a count for thrown exceptions, if that proves to be significant we can revisit. } return APP_NOTIFICATIONS_STATUS_EXCEPTION; }