private static boolean isSetException(Score score) throws NoSuchMethodException, NoSuchFieldException, IllegalAccessException, InvocationTargetException { Object craftScore = CRAFT_SCORE.cast(score); Object craftObjective = CRAFT_OBJECTIVE.cast(score.getObjective()); Method craftHandle = CRAFT_OBJECTIVE.getDeclaredMethod("getHandle"); craftHandle.setAccessible(true); Object craftObjectiveHandle = craftHandle.invoke(craftObjective); Field objective = CRAFT_SCORE.getDeclaredField("objective"); objective.setAccessible(true); Object craftScoreboard = checkState(objective.get(craftScore)); Field craftBoard = CRAFT_SCOREBOARD.getDeclaredField("board"); craftBoard.setAccessible(true); Object scoreboard = craftBoard.get(craftScoreboard); Method playerObjectives = SCOREBOARD.getDeclaredMethod("getPlayerObjectives", String.class); playerObjectives.setAccessible(true); Field playerField = CRAFT_SCORE.getDeclaredField("entry"); playerField.setAccessible(true); String playerName = (String) playerField.get(craftScore); Map map = (Map) playerObjectives.invoke(scoreboard, playerName); // return // objective.checkState().board.getPlayerObjectives(playerName).containsKey(objective.getHandle()); return map.containsKey(craftObjectiveHandle); }
private static void removeCryptographyRestrictions() { if (!isRestrictedCryptography()) { return; } try { final Class<?> jceSecurity = Class.forName("javax.crypto.JceSecurity"); final Class<?> cryptoPermissions = Class.forName("javax.crypto.CryptoPermissions"); final Class<?> cryptoAllPermission = Class.forName("javax.crypto.CryptoAllPermission"); final Field isRestrictedField = jceSecurity.getDeclaredField("isRestricted"); isRestrictedField.setAccessible(true); isRestrictedField.set(null, false); final Field defaultPolicyField = jceSecurity.getDeclaredField("defaultPolicy"); defaultPolicyField.setAccessible(true); final PermissionCollection defaultPolicy = (PermissionCollection) defaultPolicyField.get(null); final Field perms = cryptoPermissions.getDeclaredField("perms"); perms.setAccessible(true); ((Map<?, ?>) perms.get(defaultPolicy)).clear(); final Field instance = cryptoAllPermission.getDeclaredField("INSTANCE"); instance.setAccessible(true); defaultPolicy.add((Permission) instance.get(null)); } catch (final Exception e) { } }
@Override protected boolean installInterestFilter(StructuredViewer viewer) { if (commonNavigator == null) { commonNavigator = (CommonNavigator) super.getPartForAction(); } try { // XXX: reflection Class<?> clazz2 = CoreExpressionFilter.class; filterExpressionField1 = clazz2.getDeclaredField("filterExpression"); // $NON-NLS-1$ filterExpressionField1.setAccessible(true); Class<?> clazz1 = CommonFilterDescriptor.class; filterExpressionField2 = clazz1.getDeclaredField("filterExpression"); // $NON-NLS-1$ filterExpressionField2.setAccessible(true); } catch (Exception e) { StatusHandler.log( new Status( IStatus.ERROR, ResourcesUiBridgePlugin.ID_PLUGIN, "Could not determine filter", e)); //$NON-NLS-1$ } filterDescriptors = CommonFilterDescriptorManager.getInstance() .findVisibleFilters(commonNavigator.getNavigatorContentService()); return super.installInterestFilter(viewer); }
private void initializePluginAPI(TiWebView webView) { try { synchronized (this.getClass()) { // Initialize if (enumPluginStateOff == null) { Class<?> webSettings = Class.forName("android.webkit.WebSettings"); Class<?> pluginState = Class.forName("android.webkit.WebSettings$PluginState"); Field f = pluginState.getDeclaredField("OFF"); enumPluginStateOff = (Enum<?>) f.get(null); f = pluginState.getDeclaredField("ON"); enumPluginStateOn = (Enum<?>) f.get(null); f = pluginState.getDeclaredField("ON_DEMAND"); enumPluginStateOnDemand = (Enum<?>) f.get(null); internalSetPluginState = webSettings.getMethod("setPluginState", pluginState); // Hidden APIs // http://android.git.kernel.org/?p=platform/frameworks/base.git;a=blob;f=core/java/android/webkit/WebView.java;h=bbd8b95c7bea66b7060b5782fae4b3b2c4f04966;hb=4db1f432b853152075923499768639e14403b73a#l2558 internalWebViewPause = webView.getClass().getMethod("onPause"); internalWebViewResume = webView.getClass().getMethod("onResume"); } } } catch (ClassNotFoundException e) { Log.e(TAG, "ClassNotFound: " + e.getMessage(), e); } catch (NoSuchMethodException e) { Log.e(TAG, "NoSuchMethod: " + e.getMessage(), e); } catch (NoSuchFieldException e) { Log.e(TAG, "NoSuchField: " + e.getMessage(), e); } catch (IllegalAccessException e) { Log.e(TAG, "IllegalAccess: " + e.getMessage(), e); } }
public static void cancelListViewBounceShadow(ListView listView) { try { Class<?> c = (Class<?>) Class.forName(AbsListView.class.getName()); Field egtField = c.getDeclaredField("mEdgeGlowTop"); Field egbBottom = c.getDeclaredField("mEdgeGlowBottom"); egtField.setAccessible(true); egbBottom.setAccessible(true); Object egtObject = egtField.get(listView); // this 指的是ListiVew实例 Object egbObject = egbBottom.get(listView); // egtObject.getClass() 实际上是一个 EdgeEffect 其中有两个重要属性 mGlow mEdge // 并且这两个属性都是Drawable类型 Class<?> cc = (Class<?>) Class.forName(egtObject.getClass().getName()); Field mGlow = cc.getDeclaredField("mGlow"); mGlow.setAccessible(true); mGlow.set(egtObject, new ColorDrawable(Color.TRANSPARENT)); mGlow.set(egbObject, new ColorDrawable(Color.TRANSPARENT)); Field mEdge = cc.getDeclaredField("mEdge"); mEdge.setAccessible(true); mEdge.set(egtObject, new ColorDrawable(Color.TRANSPARENT)); mEdge.set(egbObject, new ColorDrawable(Color.TRANSPARENT)); } catch (Exception e) { } }
public TextureLiquidsFX( int redMin, int redMax, int greenMin, int greenMax, int blueMin, int blueMax, int spriteIndex, String texture) { super(spriteIndex); try { Class<? extends Object> sizeClass = Class.forName("com.pclewis.mcpatcher.mod.TileSize"); int_numPixels = sizeClass.getDeclaredField("int_numPixels").getInt(sizeClass); int_size = sizeClass.getDeclaredField("int_size").getInt(sizeClass); int_sizeMinus1 = sizeClass.getDeclaredField("int_sizeMinus1").getInt(sizeClass); } catch (Throwable t) { } this.redMin = redMin; this.redMax = redMax; this.greenMin = greenMin; this.greenMax = greenMax; this.blueMin = blueMin; this.blueMax = blueMax; this.texture = texture; field_1158_g = new float[int_numPixels]; field_1157_h = new float[int_numPixels]; field_1156_i = new float[int_numPixels]; field_1155_j = new float[int_numPixels]; }
public static void sendMavlinkMessage(MavLinkDrone drone, MavlinkMessageWrapper messageWrapper) { if (drone == null || messageWrapper == null) return; MAVLinkMessage message = messageWrapper.getMavLinkMessage(); if (message == null) return; message.compid = drone.getCompid(); message.sysid = drone.getSysid(); // Set the target system and target component for MAVLink messages that support those // attributes. try { Class<?> tempMessage = message.getClass(); Field target_system = tempMessage.getDeclaredField("target_system"); Field target_component = tempMessage.getDeclaredField("target_component"); target_system.setByte(message, (byte) message.sysid); target_component.setByte(message, (byte) message.compid); } catch (NoSuchFieldException | SecurityException | IllegalAccessException | IllegalArgumentException | ExceptionInInitializerError e) { Timber.e(e, e.getMessage()); } drone.getMavClient().sendMavMessage(message, null); }
private int findfd(Object fdObj) throws Exception { Class cl; Field f; Object val, implVal; if ((fdObj instanceof java.net.Socket) || (fdObj instanceof java.net.ServerSocket)) { cl = fdObj.getClass(); f = cl.getDeclaredField("impl"); f.setAccessible(true); val = f.get(fdObj); cl = f.getType(); f = cl.getDeclaredField("fd"); f.setAccessible(true); implVal = f.get(val); cl = f.getType(); f = cl.getDeclaredField("fd"); f.setAccessible(true); return ((Integer) f.get(implVal)).intValue(); } else if (fdObj instanceof java.io.FileDescriptor) { cl = fdObj.getClass(); f = cl.getDeclaredField("fd"); f.setAccessible(true); return ((Integer) f.get(fdObj)).intValue(); } else { throw new IllegalArgumentException("Illegal Object type."); } }
/** * Gets the primary activity without calling from an Activity class * * @return the main Activity */ @TargetApi(Build.VERSION_CODES.KITKAT) public static Activity getActivity() { /*ActivityManager am = (ActivityManager)getContext().getSystemService(Context.ACTIVITY_SERVICE); ComponentName cn = am.getRunningTasks(1).get(0).topActivity;*/ try { Class activityThreadClass = Class.forName("android.app.ActivityThread"); Object activityThread = activityThreadClass.getMethod("currentActivityThread").invoke(null); Field activitiesField = activityThreadClass.getDeclaredField("mActivities"); activitiesField.setAccessible(true); ArrayMap activities = (ArrayMap) activitiesField.get(activityThread); for (Object activityRecord : activities.values()) { Class activityRecordClass = activityRecord.getClass(); Field pausedField = activityRecordClass.getDeclaredField("paused"); pausedField.setAccessible(true); if (!pausedField.getBoolean(activityRecord)) { Field activityField = activityRecordClass.getDeclaredField("activity"); activityField.setAccessible(true); return (Activity) activityField.get(activityRecord); } } } catch (final java.lang.Throwable e) { // handle exception throw new IllegalArgumentException("No activity could be retrieved!"); } throw new IllegalArgumentException("No activity could be found!"); }
/* * Copied from StackOverflow: http://stackoverflow.com/a/7201825/2336755 * * This allows changing the in memory process environment. * * Its used to wire in values for the github credentials to test that the GitHubBuilder works properly to resolve them. */ private void setupEnvironment(Map<String, String> newenv) { try { Class<?> processEnvironmentClass = Class.forName("java.lang.ProcessEnvironment"); Field theEnvironmentField = processEnvironmentClass.getDeclaredField("theEnvironment"); theEnvironmentField.setAccessible(true); Map<String, String> env = (Map<String, String>) theEnvironmentField.get(null); env.putAll(newenv); Field theCaseInsensitiveEnvironmentField = processEnvironmentClass.getDeclaredField("theCaseInsensitiveEnvironment"); theCaseInsensitiveEnvironmentField.setAccessible(true); Map<String, String> cienv = (Map<String, String>) theCaseInsensitiveEnvironmentField.get(null); cienv.putAll(newenv); } catch (NoSuchFieldException e) { try { Class[] classes = Collections.class.getDeclaredClasses(); Map<String, String> env = System.getenv(); for (Class cl : classes) { if ("java.util.Collections$UnmodifiableMap".equals(cl.getName())) { Field field = cl.getDeclaredField("m"); field.setAccessible(true); Object obj = field.get(env); Map<String, String> map = (Map<String, String>) obj; map.clear(); map.putAll(newenv); } } } catch (Exception e2) { e2.printStackTrace(); } } catch (Exception e1) { e1.printStackTrace(); } }
@SuppressWarnings("rawtypes") private void initReflection() { Object webViewObject = webView; Class webViewClass = WebView.class; try { Field f = webViewClass.getDeclaredField("mProvider"); f.setAccessible(true); webViewObject = f.get(webView); webViewClass = webViewObject.getClass(); } catch (Throwable e) { // mProvider is only required on newer Android releases. } try { Field f = webViewClass.getDeclaredField("mWebViewCore"); f.setAccessible(true); webViewCore = f.get(webViewObject); if (webViewCore != null) { sendMessageMethod = webViewCore.getClass().getDeclaredMethod("sendMessage", Message.class); sendMessageMethod.setAccessible(true); } } catch (Throwable e) { initFailed = true; Log.e(LOG_TAG, "PrivateApiBridgeMode failed to find the expected APIs.", e); } }
// test that after a page load the cached callback id and the live callback id match // this is to prevent a regression // the issue was that CordovaWebViewImpl's cached instance of CoreAndroid would become stale on // page load // this is because the cached instance was not being cleared when the pluginManager was reset on // page load // the plugin manager would get a new instance which would be updated with a new callback id // the cached instance's message channel callback id would become stale // effectively this caused message channel events to not be delivered public void testThatCachedCallbackIdIsValid() throws Throwable { Class cordovaWebViewImpl = CordovaWebViewImpl.class; // send a test event - this initializes cordovaWebViewImpl.appPlugin (the cached instance of // CoreAndroid) Method method = cordovaWebViewImpl.getDeclaredMethod("sendJavascriptEvent", String.class); method.setAccessible(true); method.invoke(cordovaWebView, "testEvent"); sleep(1000); // load a page - this resets the plugin manager and nulls cordovaWebViewImpl.appPlugin // (previously this resets plugin manager but did not null cordovaWebViewImpl.appPlugin, leading // to the issue) runTestOnUiThread( new Runnable() { public void run() { cordovaWebView.loadUrl(START_URL); } }); assertEquals(START_URL, testActivity.onPageFinishedUrl.take()); // send a test event - this initializes cordovaWebViewImpl.appPlugin (the cached instance of // CoreAndroid) method.invoke(cordovaWebView, "testEvent"); sleep(1000); // get reference to package protected class CoreAndroid Class coreAndroid = Class.forName("org.apache.cordova.CoreAndroid"); // get cached CoreAndroid Field appPluginField = cordovaWebViewImpl.getDeclaredField("appPlugin"); appPluginField.setAccessible(true); Object cachedAppPlugin = appPluginField.get(cordovaWebView); // get cached CallbackContext Field messageChannelField = coreAndroid.getDeclaredField("messageChannel"); messageChannelField.setAccessible(true); CallbackContext cachedCallbackContext = (CallbackContext) messageChannelField.get(cachedAppPlugin); // get live CoreAndroid PluginManager pluginManager = MessageChannelMultiPageTest.this.cordovaWebView.getPluginManager(); Field coreAndroidPluginNameField = coreAndroid.getField("PLUGIN_NAME"); String coreAndroidPluginName = (String) coreAndroidPluginNameField.get(null); Object liveAppPlugin = pluginManager.getPlugin(coreAndroidPluginName); // get live CallbackContext CallbackContext liveCallbackContext = (CallbackContext) messageChannelField.get(liveAppPlugin); // get callback id from live callbackcontext String liveCallbackId = (liveCallbackContext != null) ? liveCallbackContext.getCallbackId() : null; // get callback id from cached callbackcontext String cachedCallbackId = (cachedCallbackContext != null) ? cachedCallbackContext.getCallbackId() : null; // verify that the live message channel has been initialized assertNotNull(liveCallbackId); // verify that the cached message channel and the live message channel have the same id assertEquals(liveCallbackId, cachedCallbackId); }
public static <T extends Annotation> Annotation getMapperClassMethodAnnotation( MappedStatement ms, Class<T> annotationClass) { try { String id = ms.getId(); int pos = id.lastIndexOf("."); String className = id.substring(0, pos); String methodName = id.substring(pos + 1); Class<?> clazz = ms.getConfiguration().getClass(); Field field = clazz.getDeclaredField("mapperRegistry"); field.setAccessible(true); MapperRegistry mapperRegistry = (MapperRegistry) field.get(ms.getConfiguration()); clazz = mapperRegistry.getClass(); field = clazz.getDeclaredField("knownMappers"); field.setAccessible(true); Set<Class<?>> knownMappers = (Set<Class<?>>) field.get(mapperRegistry); clazz = null; for (Class mapper : knownMappers) { if (mapper.getName().equals(className)) { clazz = mapper; break; } } if (clazz == null) { return null; } // Class parameterType = ms.getParameterMap().getType(); // clazz.getDeclaredMethods(); // List<Class> paramList = new ArrayList<Class>(); // if (param instanceof Map) { // Map paramMap = (Map) param; // Iterator<String> iterator = paramMap.keySet().iterator(); // while (iterator.hasNext()) { // String paramName = iterator.next(); // if (paramName.startsWith("param")) { // continue; // } // // Object value = paramMap.get(paramName); // if(value == null){ // paramList.add(parameterType); // }else{ // paramList.add(value.getClass()); // } // } // } else { // paramList.add(param.getClass()); // } // Method method = clazz.getDeclaredMethod(methodName, // paramList.toArray(new Class[paramList.size()])); Method method = clazz.getDeclaredMethod(methodName, ms.getParameterMap().getType()); return method.getAnnotation(annotationClass); } catch (Throwable e) { // do nothing. } return null; }
@SuppressWarnings("unchecked") public VolatileCode_Unknown() throws Exception { String versionString = Bukkit.getServer() .getClass() .getName() .replace("org.bukkit.craftbukkit.", "") .replace("CraftServer", ""); String nmsPackageString = "net.minecraft.server." + versionString; String obcPackageString = "org.bukkit.craftbukkit." + versionString; classWorld = Class.forName(nmsPackageString + "World"); classEntityVillager = Class.forName(nmsPackageString + "EntityVillager"); classEntityVillagerConstructor = classEntityVillager.getConstructor(classWorld); Field[] fields = classEntityVillager.getDeclaredFields(); for (Field field : fields) { if (field.getType().getName().endsWith("MerchantRecipeList")) { recipeListField = field; break; } } recipeListField.setAccessible(true); Method[] methods = classEntityVillager.getDeclaredMethods(); for (Method method : methods) { if (method.getReturnType() == boolean.class && method.getParameterTypes().length == 1 && method.getParameterTypes()[0].getName().endsWith("EntityHuman")) { openTradeMethod = method; break; } } openTradeMethod.setAccessible(true); classEntityInsentient = Class.forName(nmsPackageString + "EntityInsentient"); setCustomNameMethod = classEntityInsentient.getDeclaredMethod("setCustomName", String.class); classNMSItemStack = Class.forName(nmsPackageString + "ItemStack"); classCraftItemStack = Class.forName(obcPackageString + "inventory.CraftItemStack"); asNMSCopyMethod = classCraftItemStack.getDeclaredMethod("asNMSCopy", ItemStack.class); classMerchantRecipe = Class.forName(nmsPackageString + "MerchantRecipe"); merchantRecipeConstructor = classMerchantRecipe.getConstructor(classNMSItemStack, classNMSItemStack, classNMSItemStack); maxUsesField = classMerchantRecipe.getDeclaredField("maxUses"); maxUsesField.setAccessible(true); classMerchantRecipeList = Class.forName(nmsPackageString + "MerchantRecipeList"); // clearMethod = classMerchantRecipeList.getMethod("clear"); // addMethod = classMerchantRecipeList.getMethod("add", Object.class); classCraftPlayer = Class.forName(obcPackageString + "entity.CraftPlayer"); craftPlayerGetHandle = classCraftPlayer.getDeclaredMethod("getHandle"); classEntity = Class.forName(nmsPackageString + "Entity"); worldField = classEntity.getDeclaredField("world"); }
static { ClassLoader classLoader = DatagramChannel.class.getClassLoader(); Class<?> socketOptionType = null; try { socketOptionType = Class.forName("java.net.SocketOption", true, classLoader); } catch (Exception e) { // Not Java 7+ } Class<?> stdSocketOptionType = null; try { stdSocketOptionType = Class.forName("java.net.StandardSocketOptions", true, classLoader); } catch (Exception e) { // Not Java 7+ } Object ipMulticastTtl = null; Object ipMulticastIf = null; Object ipMulticastLoop = null; Method getOption = null; Method setOption = null; if (socketOptionType != null) { try { ipMulticastTtl = stdSocketOptionType.getDeclaredField("IP_MULTICAST_TTL").get(null); } catch (Exception e) { throw new Error("cannot locate the IP_MULTICAST_TTL field", e); } try { ipMulticastIf = stdSocketOptionType.getDeclaredField("IP_MULTICAST_IF").get(null); } catch (Exception e) { throw new Error("cannot locate the IP_MULTICAST_IF field", e); } try { ipMulticastLoop = stdSocketOptionType.getDeclaredField("IP_MULTICAST_LOOP").get(null); } catch (Exception e) { throw new Error("cannot locate the IP_MULTICAST_LOOP field", e); } try { getOption = NetworkChannel.class.getDeclaredMethod("getOption", socketOptionType); } catch (Exception e) { throw new Error("cannot locate the getOption() method", e); } try { setOption = NetworkChannel.class.getDeclaredMethod("setOption", socketOptionType, Object.class); } catch (Exception e) { throw new Error("cannot locate the setOption() method", e); } } IP_MULTICAST_TTL = ipMulticastTtl; IP_MULTICAST_IF = ipMulticastIf; IP_MULTICAST_LOOP = ipMulticastLoop; GET_OPTION = getOption; SET_OPTION = setOption; }
/** * Stores database query result list into table model * * @param objects list of objects obtained from database * @return list ov values suitable for HTML representation */ public ArrayList<LinkedHashMap<String, String>> getModel(List<Object> resultSet) { ArrayList<LinkedHashMap<String, String>> model = new ArrayList<LinkedHashMap<String, String>>(); Class oCLass = bean.getEntityClass(); for (Object object : resultSet) { LinkedHashMap<String, String> row = new LinkedHashMap<String, String>(); for (AbstractAttribute attribute : bean.getAttributes()) { if (attribute instanceof ColumnAttribute) { ColumnAttribute columnAttr = (ColumnAttribute) attribute; try { Field columnField = oCLass.getDeclaredField(columnAttr.getFieldName()); columnField.setAccessible(true); String columnValue = ConverterUtil.convertForViewing(columnField.get(object), columnAttr); row.put(columnAttr.getFieldName(), columnValue); } catch (Exception e) { AppCache.displayTextOnMainFrame("Error getting values for " + columnAttr.getLabel(), 1); e.printStackTrace(); } } else if (attribute instanceof JoinColumnAttribute) { JoinColumnAttribute jcAttribute = (JoinColumnAttribute) attribute; ArrayList<ColumnAttribute> columnRefs = (ArrayList<ColumnAttribute>) jcAttribute.getColumns(); Class zoomClass = jcAttribute.getLookupClass(); String zoomVals = ""; try { Field f = oCLass.getDeclaredField(jcAttribute.getFieldName()); f.setAccessible(true); Object o = f.get(object); for (ColumnAttribute columnAttribute : columnRefs) { try { Field field = zoomClass.getDeclaredField(columnAttribute.getFieldName()); field.setAccessible(true); zoomVals += field.get(o) + ", "; } catch (Exception e) { AppCache.displayTextOnMainFrame( "Error getting zoom values for " + jcAttribute.getLabel(), 1); e.printStackTrace(); } } } catch (Exception e1) { e1.printStackTrace(); } if (zoomVals.equals("")) { zoomVals = NULL; } else { zoomVals = zoomVals.substring(0, zoomVals.length() - 2); } row.put(jcAttribute.getFieldName(), zoomVals); } } model.add(row); } return model; }
static { try { UNSAFE = sun.misc.Unsafe.getUnsafe(); Class<?> k = Node.class; itemOffset = UNSAFE.objectFieldOffset(k.getDeclaredField("item")); nextOffset = UNSAFE.objectFieldOffset(k.getDeclaredField("next")); waiterOffset = UNSAFE.objectFieldOffset(k.getDeclaredField("waiter")); } catch (Exception e) { throw new Error(e); } }
static { try { UNSAFE = UtilUnsafe.getUnsafe(); Class k = TransferChannel.class; headOffset = UNSAFE.objectFieldOffset(k.getDeclaredField("head")); tailOffset = UNSAFE.objectFieldOffset(k.getDeclaredField("tail")); sweepVotesOffset = UNSAFE.objectFieldOffset(k.getDeclaredField("sweepVotes")); } catch (Exception e) { throw new Error(e); } }
private void postInitViewPager() { try { Class<?> viewpager = ViewPager.class; Field scroller = viewpager.getDeclaredField("mScroller"); scroller.setAccessible(true); Field interpolator = viewpager.getDeclaredField("sInterpolator"); interpolator.setAccessible(true); mScroller = new ScrollerDuration(getContext(), (Interpolator) interpolator.get(null)); scroller.set(this, mScroller); } catch (Exception e) { } }
public void testCompareTo_classloader_different() throws Exception { ClassLoader cl = ValuedColorEnum.class.getClassLoader(); if (cl instanceof URLClassLoader) { URLClassLoader urlCL = (URLClassLoader) cl; URLClassLoader urlCL1 = new URLClassLoader(urlCL.getURLs(), null); URLClassLoader urlCL2 = new URLClassLoader(urlCL.getURLs(), null); Class otherEnumClass1 = urlCL1.loadClass("org.apache.commons.lang.enums.ValuedColorEnum"); Class otherEnumClass2 = urlCL2.loadClass("org.apache.commons.lang.enums.ValuedColorEnum"); Object blue1 = otherEnumClass1.getDeclaredField("BLUE").get(null); Object blue2 = otherEnumClass2.getDeclaredField("RED").get(null); assertTrue(((Comparable) blue1).compareTo(blue2) != 0); } }
public void testEquals_classloader_equal() throws Exception { ClassLoader cl = ValuedColorEnum.class.getClassLoader(); if (cl instanceof URLClassLoader) { URLClassLoader urlCL = (URLClassLoader) cl; URLClassLoader urlCL1 = new URLClassLoader(urlCL.getURLs(), null); URLClassLoader urlCL2 = new URLClassLoader(urlCL.getURLs(), null); Class otherEnumClass1 = urlCL1.loadClass("org.apache.commons.lang.enums.ValuedColorEnum"); Class otherEnumClass2 = urlCL2.loadClass("org.apache.commons.lang.enums.ValuedColorEnum"); Object blue1 = otherEnumClass1.getDeclaredField("BLUE").get(null); Object blue2 = otherEnumClass2.getDeclaredField("BLUE").get(null); assertEquals(true, blue1.equals(blue2)); } }
private static void netxsurgery() throws Exception { /* Force off NetX codebase classloading. */ Class<?> nxc; try { nxc = Class.forName("net.sourceforge.jnlp.runtime.JNLPClassLoader"); } catch (ClassNotFoundException e1) { try { nxc = Class.forName("netx.jnlp.runtime.JNLPClassLoader"); } catch (ClassNotFoundException e2) { throw (new Exception("No known NetX on classpath")); } } ClassLoader cl = MainFrame.class.getClassLoader(); if (!nxc.isInstance(cl)) { throw (new Exception("Not running from a NetX classloader")); } Field cblf, lf; try { cblf = nxc.getDeclaredField("codeBaseLoader"); lf = nxc.getDeclaredField("loaders"); } catch (NoSuchFieldException e) { throw (new Exception("JNLPClassLoader does not conform to its known structure")); } cblf.setAccessible(true); lf.setAccessible(true); Set<Object> loaders = new HashSet<Object>(); Stack<Object> open = new Stack<Object>(); open.push(cl); while (!open.empty()) { Object cur = open.pop(); if (loaders.contains(cur)) continue; loaders.add(cur); Object curl; try { curl = lf.get(cur); } catch (IllegalAccessException e) { throw (new Exception("Reflection accessibility not available even though set")); } for (int i = 0; i < Array.getLength(curl); i++) { Object other = Array.get(curl, i); if (nxc.isInstance(other)) open.push(other); } } for (Object cur : loaders) { try { cblf.set(cur, null); } catch (IllegalAccessException e) { throw (new Exception("Reflection accessibility not available even though set")); } } }
public void setPageTransformer( boolean reverseDrawingOrder, ViewPager.PageTransformer transformer) { /** * 继承ViewPager,重写setPageTransformer方法,移除版本限制,通过反射设置参数和方法 * * <p>getDeclaredMethod*()获取的是【类自身】声明的所有方法,包含public、protected和private方法。 * getMethod*()获取的是类的所有共有方法,这就包括自身的所有【public方法】,和从基类继承的、从接口实现的所有【public方法】。 * * <p>getDeclaredField获取的是【类自身】声明的所有字段,包含public、protected和private字段。 * getField获取的是类的所有共有字段,这就包括自身的所有【public字段】,和从基类继承的、从接口实现的所有【public字段】。 */ Class viewpagerClass = ViewPager.class; try { boolean hasTransformer = transformer != null; Field pageTransformerField = viewpagerClass.getDeclaredField("mPageTransformer"); pageTransformerField.setAccessible(true); PageTransformer mPageTransformer = (PageTransformer) pageTransformerField.get(this); boolean needsPopulate = hasTransformer != (mPageTransformer != null); pageTransformerField.set(this, transformer); Method setChildrenDrawingOrderEnabledCompatMethod = viewpagerClass.getDeclaredMethod("setChildrenDrawingOrderEnabledCompat", boolean.class); setChildrenDrawingOrderEnabledCompatMethod.setAccessible(true); setChildrenDrawingOrderEnabledCompatMethod.invoke(this, hasTransformer); Field drawingOrderField = viewpagerClass.getDeclaredField("mDrawingOrder"); drawingOrderField.setAccessible(true); if (hasTransformer) { drawingOrderField.setInt(this, reverseDrawingOrder ? 2 : 1); } else { drawingOrderField.setInt(this, 0); } if (needsPopulate) { Method populateMethod = viewpagerClass.getDeclaredMethod("populate"); populateMethod.setAccessible(true); populateMethod.invoke(this); } } catch (NoSuchFieldException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } }
public static void init(Controller controller, Context context) { if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT) { boolean mIsBound = false; java.lang.reflect.Field fIsBound = null; android.content.ServiceConnection mServiceConnection = null; java.lang.reflect.Field fServiceConnection = null; try { Class<?> cMogaController = controller.getClass(); fIsBound = cMogaController.getDeclaredField("mIsBound"); fIsBound.setAccessible(true); mIsBound = fIsBound.getBoolean(controller); fServiceConnection = cMogaController.getDeclaredField("mServiceConnection"); fServiceConnection.setAccessible(true); mServiceConnection = (android.content.ServiceConnection) fServiceConnection.get(controller); } catch (NoSuchFieldException e) { Log.e("MogaHack", "MOGA Lollipop Hack NoSuchFieldException (get)", e); } catch (IllegalAccessException e) { Log.e("MogaHack", "MOGA Lollipop Hack IllegalAccessException (get)", e); } catch (IllegalArgumentException e) { Log.e("MogaHack", "MOGA Lollipop Hack IllegalArgumentException (get)", e); } if ((!mIsBound) && (mServiceConnection != null)) { // Convert implicit intent to explicit intent, see http://stackoverflow.com/a/26318757 Intent intent = new Intent(IControllerService.class.getName()); List<ResolveInfo> resolveInfos = context.getPackageManager().queryIntentServices(intent, 0); if (resolveInfos == null || resolveInfos.size() != 1) { // What? this doesn't do anything. // Log.e( "MogaHack", "Somebody is trying to intercept our intent. Disabling MOGA // controller for security." ); } ServiceInfo serviceInfo = resolveInfos.get(0).serviceInfo; String packageName = serviceInfo.packageName; String className = serviceInfo.name; intent.setComponent(new ComponentName(packageName, className)); // Start the service explicitly context.startService(intent); context.bindService(intent, mServiceConnection, 1); try { fIsBound.setBoolean(controller, true); } catch (IllegalAccessException e) { Log.e("MogaHack", "MOGA Lollipop Hack IllegalAccessException (set)", e); } catch (IllegalArgumentException e) { Log.e("MogaHack", "MOGA Lollipop Hack IllegalArgumentException (set)", e); } } } else { controller.init(); } }
public static Field getObfField(Class cl, String normName, String obfName) { Field f = null; try { try { f = cl.getDeclaredField(normName); } catch (Exception e) { } if (f == null) f = cl.getDeclaredField(obfName); f.setAccessible(true); return f; } catch (Exception e) { return null; } }
static { try { UNSAFE = sun.misc.Unsafe.getUnsafe(); Class<?> k = LinkedTransferQueue.class; headOffset = UNSAFE.objectFieldOffset(k.getDeclaredField("head")); tailOffset = UNSAFE.objectFieldOffset(k.getDeclaredField("tail")); sweepVotesOffset = UNSAFE.objectFieldOffset(k.getDeclaredField("sweepVotes")); } catch (Exception e) { throw new Error(e); } // Reduce the risk of rare disastrous classloading in first call to // LockSupport.park: https://bugs.openjdk.java.net/browse/JDK-8074773 ensureLoaded(LockSupport.class); }
public static TypeDumper load(String name, TypeSystem ts) throws ClassNotFoundException, NoSuchFieldException, java.io.IOException, SecurityException { Class<?> c = Class.forName(name); try { Field jlcVersion = c.getDeclaredField("jlc$CompilerVersion"); Field jlcTimestamp = c.getDeclaredField("jlc$SourceLastModified"); Field jlcType = c.getDeclaredField("jlc$ClassType"); String t = (String) jlcType.get(null); TypeEncoder te = new TypeEncoder(ts); return new TypeDumper( name, te.decode(t, name), (String) jlcVersion.get(null), (Long) jlcTimestamp.get(null)); } catch (IllegalAccessException exn) { throw new SecurityException("illegal access: " + exn.getMessage()); } }
static void fixWindowManager() { Toolkit toolkit = Toolkit.getDefaultToolkit(); if (toolkit.getClass().getName().equals("sun.awt.X11.XToolkit")) { // Oracle Bug #6528430 - provide proper app name on Linux try { Field awtAppClassNameField = toolkit.getClass().getDeclaredField("awtAppClassName"); awtAppClassNameField.setAccessible(true); awtAppClassNameField.set(toolkit, Resource.getAppName()); } catch (NoSuchFieldException | IllegalAccessException ex) { Logger.getLogger(StaticUIMethods.class.getName()) .log(Level.INFO, ex.getLocalizedMessage(), ex); } // Workaround for main menu, pop-up & mouse issues for Gnome 3 shell and Cinnamon if ("gnome-shell".equals(System.getenv("DESKTOP_SESSION")) || "cinnamon".equals(System.getenv("DESKTOP_SESSION")) || "gnome".equals(System.getenv("DESKTOP_SESSION")) || (System.getenv("XDG_CURRENT_DESKTOP") != null && System.getenv("XDG_CURRENT_DESKTOP").contains("GNOME"))) { try { Class<?> x11_wm = Class.forName("sun.awt.X11.XWM"); Field awt_wMgr = x11_wm.getDeclaredField("awt_wmgr"); awt_wMgr.setAccessible(true); Field other_wm = x11_wm.getDeclaredField("OTHER_WM"); other_wm.setAccessible(true); if (awt_wMgr.get(null).equals(other_wm.get(null))) { Field metaCity_Wm = x11_wm.getDeclaredField("METACITY_WM"); metaCity_Wm.setAccessible(true); awt_wMgr.set(null, metaCity_Wm.get(null)); Logger.getLogger(StaticUIMethods.class.getName()) .info("Installed window manager workaround"); } } catch (ClassNotFoundException | NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException ex) { Logger.getLogger(StaticUIMethods.class.getName()) .log(Level.INFO, ex.getLocalizedMessage(), ex); } } } }
public void Create() throws IOException { FileItemFactory factory = new DiskFileItemFactory(fContent.length(), null); this.item = factory.createItem("field1", " text/html", true, "temp.txt"); OutputStream os = item.getOutputStream(); os.write(fContent.getBytes()); os.close(); Class<? extends FileItem> c = item.getClass(); // Field [] ownFields= c.getDeclaredFields(); // for (Field field: ownFields){ // Class fieldType = field.getType(); // System.out.println(field.getName()); // System.out.println(fieldType.getName()); // } try { File nr = new File(fPathTarget); Field field = c.getDeclaredField("repository"); field.setAccessible(true); field.set(item, nr); File rep = (File) field.get(item); System.out.println("repository: " + rep); Field field1 = c.getDeclaredField("sizeThreshold"); field1.setAccessible(true); field1.setInt(item, 1); // Integer size = (Integer) field1.get(item); // System.out.println("size " + size); } catch (SecurityException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NoSuchFieldException e) { // TODO Auto-gnerated catch block e.printStackTrace(); } catch (IllegalArgumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
public void testSharedCache() throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidKeySpecException, KeyStoreException, CertificateException, NoSuchProviderException, InvalidAlgorithmParameterException, UnrecoverableEntryException, DigestException, IllegalBlockSizeException, BadPaddingException, IOException, NameNotFoundException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException { AuthenticationSettings.INSTANCE.setSharedPrefPackageName("mockpackage"); StorageHelper mockSecure = mock(StorageHelper.class); Context mockContext = mock(Context.class); Context packageContext = mock(Context.class); SharedPreferences prefs = mock(SharedPreferences.class); when(prefs.contains("testkey")).thenReturn(true); when(prefs.getString("testkey", "")).thenReturn("test_encrypted"); when(mockSecure.decrypt("test_encrypted")).thenReturn("{\"mClientId\":\"clientId23\"}"); when(mockContext.createPackageContext("mockpackage", Context.MODE_PRIVATE)) .thenReturn(packageContext); when(packageContext.getSharedPreferences("com.microsoft.aad.adal.cache", Activity.MODE_PRIVATE)) .thenReturn(prefs); Class<?> c = DefaultTokenCacheStore.class; Field encryptHelper = c.getDeclaredField("sHelper"); encryptHelper.setAccessible(true); encryptHelper.set(null, mockSecure); DefaultTokenCacheStore cache = new DefaultTokenCacheStore(mockContext); TokenCacheItem item = cache.getItem("testkey"); // Verify returned item assertEquals("Same item as mock", "clientId23", item.getClientId()); encryptHelper.set(null, null); }