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); }
/** * Launch a browser window to show the given url * * @param inUrl url to show */ public static void launchBrowser(String inUrl) { // First choice is to try the Desktop library from java 6, if available try { Class<?> d = Class.forName("java.awt.Desktop"); d.getDeclaredMethod("browse", new Class[] {URI.class}) .invoke(d.getDeclaredMethod("getDesktop").invoke(null), new Object[] {URI.create(inUrl)}); // above code mimics: Desktop.getDesktop().browse(URI.create(inUrl)); } catch (Exception ignore) { // The Desktop call failed, need to try backup methods if (!_initialised) { init(); } if (_browserCommand == null) { JOptionPane.showMessageDialog(null, "Cannot show url: " + inUrl); } else { try { // enclose url in quotes if necessary String url = inUrl; if (_urlNeedsQuotes) { url = "\"" + url + "\""; } // Fill in url in last element of command array _browserCommand[_browserCommand.length - 1] = url; // execute command to launch browser Runtime.getRuntime().exec(_browserCommand); } catch (Exception e) { JOptionPane.showMessageDialog(null, "Failed to show url: " + inUrl); } } } }
public String getUserNameFull() { String s = "Это Линокс"; if (isOSWindows()) { String className = "com.sun.security.auth.module.NTSystem"; try { ClassLoader cL = ClassLoader.getSystemClassLoader(); Class cls = cL.loadClass(className); Object obj = cls.newInstance(); Method methodGetName = cls.getDeclaredMethod("getName"); s = (String) methodGetName.invoke(obj); Method methodGetDomain = cls.getDeclaredMethod("getDomain"); s = (String) methodGetDomain.invoke(obj) + "\\" + s; } catch (ClassNotFoundException e) { return "undefined"; } catch (InstantiationException e) { return "undefined"; } catch (IllegalAccessException e) { return "undefined"; } catch (NoSuchMethodException e) { return "undefined"; } catch (InvocationTargetException e) { return "undefined"; } } return s; }
public BaseClusterReceiver(ExecutorService executorService) { if (executorService == null) { throw new NullPointerException("Executor service is null"); } _executorService = executorService; boolean hasDoViewAccepted = false; Class<?> clazz = getClass(); try { clazz.getDeclaredMethod("doAddressesUpdated", List.class, List.class); hasDoViewAccepted = true; } catch (ReflectiveOperationException roe) { } _hasDoViewAccepted = hasDoViewAccepted; boolean hasDoCoordinatorAddressUpdated = false; try { clazz.getDeclaredMethod("doCoordinatorAddressUpdated", Address.class, Address.class); hasDoCoordinatorAddressUpdated = true; } catch (ReflectiveOperationException roe) { } _hasDoCoordinatorAddressUpdated = hasDoCoordinatorAddressUpdated; }
/** * 将查询结构设置给对应的域(一对多) * * @param list * @param majorMethod * @param fieldName * @param childEntities * @param childClass * @param foreignKey * @throws NoSuchMethodException * @throws InvocationTargetException * @throws IllegalAccessException */ private void setListValue( List<T> list, Method majorMethod, String fieldName, List<Entity> childEntities, Class<Entity> childClass, String foreignKey) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { Map<Object, List<Entity>> childListMap = new HashMap<Object, List<Entity>>(); for (Entity childEntity : childEntities) { Method foreignKeyMethod = childClass.getDeclaredMethod("get".concat(StringUtils.firstToUpperCase(foreignKey))); Object id = foreignKeyMethod.invoke(childEntity); List<Entity> childList = childListMap.get(id); if (childList == null) { childList = new ArrayList<Entity>(); childListMap.put(id, childList); } childList.add(childEntity); } String listMethodName = "set".concat(StringUtils.firstToUpperCase(fieldName)); for (T entity : list) { Object id = majorMethod.invoke(entity); List<Entity> childLis = childListMap.get(id); Method listMethod = entityClass.getDeclaredMethod(listMethodName, List.class); listMethod.invoke(entity, childLis); } }
/* * UiAutomator has a broken longClick. getAutomatorBridge is private so we * access the bridge via reflection to use the touchDown / touchUp methods. */ private boolean correctLongClick(final int x, final int y, final int duration) { try { /* * bridge.getClass() returns ShellUiAutomatorBridge on API 18/19 so use * the super class. */ final UiDevice device = UiDevice.getInstance(); final Object bridge = enableField(device.getClass(), "mUiAutomationBridge").get(device); final Object controller = enableField(bridge.getClass().getSuperclass(), "mInteractionController").get(bridge); final Class<?> controllerClass = controller.getClass(); Logger.debug("Finding methods on class: " + controllerClass); final Method touchDown = controllerClass.getDeclaredMethod("touchDown", int.class, int.class); touchDown.setAccessible(true); final Method touchUp = controllerClass.getDeclaredMethod("touchUp", int.class, int.class); touchUp.setAccessible(true); if ((Boolean) touchDown.invoke(controller, x, y)) { SystemClock.sleep(duration); if ((Boolean) touchUp.invoke(controller, x, y)) { return true; } } return false; } catch (final Exception e) { Logger.debug("Problem invoking correct long click: " + e); return false; } }
/*package*/ static boolean isModern(Class<? extends LoadStatistics> clazz) { // cannot use Util.isOverridden as these are protected methods. boolean hasGetNodes = false; boolean hasMatches = false; while (clazz != LoadStatistics.class && clazz != null && !(hasGetNodes && hasMatches)) { if (!hasGetNodes) { try { final Method getNodes = clazz.getDeclaredMethod("getNodes"); hasGetNodes = !Modifier.isAbstract(getNodes.getModifiers()); } catch (NoSuchMethodException e) { // ignore } } if (!hasMatches) { try { final Method getNodes = clazz.getDeclaredMethod("matches", Queue.Item.class, SubTask.class); hasMatches = !Modifier.isAbstract(getNodes.getModifiers()); } catch (NoSuchMethodException e) { // ignore } } if (!(hasGetNodes && hasMatches) && LoadStatistics.class.isAssignableFrom(clazz.getSuperclass())) { clazz = (Class<? extends LoadStatistics>) clazz.getSuperclass(); } } return hasGetNodes && hasMatches; }
/** * 将查询结构设置给对应的域(一对一/多对一) * * @param list * @param keyMethod * @param fieldName * @param childEntities * @param childClass * @param fileType * @param refKey * @throws NoSuchMethodException * @throws InvocationTargetException * @throws IllegalAccessException */ private void setSingleValue( List<T> list, Method keyMethod, String fieldName, List<Entity> childEntities, Class<Entity> childClass, Class<?> fileType, String refKey) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { Map<Object, Entity> childMap = new HashMap<Object, Entity>(); for (Entity childEntity : childEntities) { Method refKeyMethod = childClass.getDeclaredMethod("get".concat(StringUtils.firstToUpperCase(refKey))); Object id = refKeyMethod.invoke(childEntity); childMap.put(id, childEntity); } String fieldMethodName = "set".concat(StringUtils.firstToUpperCase(fieldName)); for (T entity : list) { Object id = keyMethod.invoke(entity); Entity child = childMap.get(id); Method fieldMethod = entityClass.getDeclaredMethod(fieldMethodName, fileType); fieldMethod.invoke(entity, child); } }
public static Object invokeMethod( Object obj, String methodName, Class<?>[] argsClasses, Object[] args) { Class<?> objClass = (obj instanceof Class) ? (Class<?>) obj : obj.getClass(); if (argsClasses == null) { if (args != null && args.length > 0) { argsClasses = new Class[args.length]; for (int i = 0; i < args.length; i++) { argsClasses[i] = args[i].getClass(); } } } try { if (argsClasses == null || argsClasses.length == 0) { Method objMethod = objClass.getDeclaredMethod(methodName); objMethod.setAccessible(true); return objMethod.invoke(obj); } else { Method objMethod = objClass.getDeclaredMethod(methodName, argsClasses); objMethod.setAccessible(true); return objMethod.invoke(obj, args); } } catch (InvocationTargetException e) { Throwable t = e.getTargetException(); if (t instanceof RuntimeException) { throw (RuntimeException) t; } throw new IllegalArgumentException(t.getMessage(), t); } catch (RuntimeException e) { throw (RuntimeException) e; } catch (Exception e) { throw new IllegalArgumentException(e.getMessage(), e); } }
static { sInitialized = false; if (!SystemProperties.getBoolean("config.disable_renderscript", false)) { try { Class<?> vm_runtime = Class.forName("dalvik.system.VMRuntime"); Method get_runtime = vm_runtime.getDeclaredMethod("getRuntime"); sRuntime = get_runtime.invoke(null); registerNativeAllocation = vm_runtime.getDeclaredMethod("registerNativeAllocation", Integer.TYPE); registerNativeFree = vm_runtime.getDeclaredMethod("registerNativeFree", Integer.TYPE); } catch (Exception e) { Log.e(LOG_TAG, "Error loading GC methods: " + e); throw new RSRuntimeException("Error loading GC methods: " + e); } try { System.loadLibrary("rs_jni"); _nInit(); sInitialized = true; sPointerSize = rsnSystemGetPointerSize(); } catch (UnsatisfiedLinkError e) { Log.e(LOG_TAG, "Error loading RS jni library: " + e); throw new RSRuntimeException("Error loading RS jni library: " + e); } } }
private static void reregisterNativeMethodsForRestoredClass(@Nonnull Class<?> realClass) { Method registerNatives = null; try { registerNatives = realClass.getDeclaredMethod("registerNatives"); } catch (NoSuchMethodException ignore) { try { registerNatives = realClass.getDeclaredMethod("initIDs"); } catch (NoSuchMethodException ignored) { } // OK } if (registerNatives != null) { try { registerNatives.setAccessible(true); registerNatives.invoke(null); } catch (IllegalAccessException ignore) { } // won't happen catch (InvocationTargetException ignore) { } // shouldn't happen either } // OK, although another solution will be required for this particular class if it requires // natives to be explicitly registered again (not all do, such as java.lang.Float). }
/** * Opens the specified web page in the user's default browser * * @param url A web address (URL) of a web page (ex: "http://www.google.com/") */ public static void openURL(String url) { try { // attempt to use Desktop library from JDK 1.6+ (even if on 1.5) Class<?> d = Class.forName("java.awt.Desktop"); d.getDeclaredMethod("browse", new Class[] {java.net.URI.class}) .invoke( d.getDeclaredMethod("getDesktop").invoke(null), new Object[] {java.net.URI.create(url)}); // above code mimics: // java.awt.Desktop.getDesktop().browse(java.net.URI.create(url)); } catch (Exception ignore) { // library not available or failed String osName = System.getProperty("os.name"); try { if (osName.startsWith("Mac OS")) { Class.forName("com.apple.eio.FileManager") .getDeclaredMethod("openURL", new Class[] {String.class}) .invoke(null, new Object[] {url}); } else if (osName.startsWith("Windows")) Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + url); else { // assume Unix or Linux boolean found = false; for (String browser : browsers) if (!found) { found = Runtime.getRuntime().exec(new String[] {"which", browser}).waitFor() == 0; if (found) Runtime.getRuntime().exec(new String[] {browser, url}); } if (!found) throw new Exception(Arrays.toString(browsers)); } } catch (Exception e) { JOptionPane.showMessageDialog(null, errMsg + "\n" + e.toString()); } } }
/** * Retrieves setter method of a field. * * @param classType class type * @param fieldName field name * @param paramType return type * @return Method setter method of field * @throws NoSuchMethodException thrown if method is not found */ public static Method getSetterMethod(Class<?> classType, String fieldName, Class<?> paramType) throws NoSuchMethodException { String methodName = "set" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1); Method m = null; NoSuchMethodException firstException = null; while (paramType != null && m == null) { try { m = classType.getDeclaredMethod(methodName, paramType); } catch (NoSuchMethodException e) { if (firstException == null) { firstException = e; } for (Class<?> interfaceClass : paramType.getInterfaces()) { try { m = classType.getDeclaredMethod(methodName, interfaceClass); } catch (NoSuchMethodException e1) { } } paramType = paramType.getSuperclass(); } } if (m == null && firstException != null) { throw firstException; } return m; }
@Override public Method resolveInternal() { Class<?> parentClass = parent.resolve(); if (parentClass == null) return null; List<Class<?>> argClasses = Lists.newLinkedList(); for (ClassRef argType : argTypes) { if (argType.resolve() == null) return null; argClasses.add(argType.resolve()); } Class<?>[] args = argClasses.toArray(new Class<?>[0]); Method methodObj; try { methodObj = parentClass.getDeclaredMethod(srgName, args); methodObj.setAccessible(true); return methodObj; } catch (Exception e) { } try { methodObj = parentClass.getDeclaredMethod(mcpName, args); methodObj.setAccessible(true); return methodObj; } catch (Exception e) { } return null; }
public static boolean updateLanguage(Locale locale) { try { Object objIActMag, objActMagNative; Class<?> clzIActMag = Class.forName("android.app.IActivityManager"); Class<?> clzActMagNative = Class.forName("android.app.ActivityManagerNative"); Method mtdActMagNative$getDefault = clzActMagNative.getDeclaredMethod("getDefault"); // IActivityManager iActMag = ActivityManagerNative.getDefault(); objIActMag = mtdActMagNative$getDefault.invoke(clzActMagNative); // Configuration config = iActMag.getConfiguration(); Method mtdIActMag$getConfiguration = clzIActMag.getDeclaredMethod("getConfiguration"); Configuration config = (Configuration) mtdIActMag$getConfiguration.invoke(objIActMag); config.locale = locale; // iActMag.updateConfiguration(config); // 此处需要声明权限:android.permission.CHANGE_CONFIGURATION // 会重新调用 onCreate(); Class<?>[] clzParams = {Configuration.class}; Method mtdIActMag$updateConfiguration = clzIActMag.getDeclaredMethod("updateConfiguration", clzParams); mtdIActMag$updateConfiguration.invoke(objIActMag, config); return true; } catch (Exception e) { e.printStackTrace(); } return false; }
/** 初始化class的method和verfiyclass的method */ private static void initMethod() { Set<Entry<Object, Object>> set = prop.entrySet(); String key = null; String value = null; for (Entry<Object, Object> entry : set) { key = String.valueOf(entry.getKey()); value = null != entry.getValue() ? String.valueOf(entry.getValue()) : null; if (endWithString(key, value, SUFFIX_CLASS)) { Class<?> c; Method method = null; try { c = Class.forName(value); method = c.getDeclaredMethod(PROCESS, Param.class); } catch (Exception e) { System.err.println("init class error:" + value); e.printStackTrace(); } classMap.put(key, method); } else if (endWithString(key, value, SUFFIX_VERIFY_CLASS)) { Class<?> c; Method method = null; try { c = Class.forName(value); method = c.getDeclaredMethod(VERIFY, Param.class); } catch (Exception e) { System.err.println("init class error:" + value); e.printStackTrace(); } verifyClassMap.put(key, method); } } set = null; key = value = null; }
public static boolean validClass(Class<?> clazz) { try { Method serialize = clazz.getDeclaredMethod("serialize"); if (!serialize.getReturnType().equals(String.class)) { System.out.println( "Class '" + clazz.getCanonicalName() + "' is not serializable because it does not return a String"); return false; } if (!Modifier.isPublic(serialize.getModifiers())) { System.out.println( "Class '" + clazz.getCanonicalName() + "' is not serializable because the method 'serialize' is not public"); return false; } if (!Modifier.isStatic(serialize.getModifiers())) { System.out.println( "Class '" + clazz.getCanonicalName() + "' is not serializable because the method 'serialize' is static"); return false; } Method deserialize = clazz.getDeclaredMethod("deserialize", String.class); if (!deserialize.getReturnType().equals(clazz)) { System.out.println( "Class '" + clazz.getCanonicalName() + "' is not deserializable because the method 'deserialize' does not return the class '" + clazz.getCanonicalName() + "'"); return false; } if (!Modifier.isStatic(deserialize.getModifiers())) { System.out.println( "Class '" + clazz.getCanonicalName() + "' is not deserializable because the method 'deserialize' is not static"); return false; } if (!Modifier.isPublic(deserialize.getModifiers())) { System.out.println( "Class '" + clazz.getCanonicalName() + "' is not deserializable because the method 'deserialize' is not public"); return false; } } catch (NoSuchMethodException e) { System.out.println( "Class '" + clazz.getCanonicalName() + "' is not deserializable because the method 'deserialize' is does not have either the serialize and/or deserialize method(s)"); return false; } return true; }
public static void main(String[] args) throws Exception { int[] team1 = {7, 2, 3}; int[] team2 = {1, 6, 4}; System.out.println("dumbPhotoShoot = " + dumbPhotoShoot(team1, team2)); System.out.println("photoShoot = " + photoShoot(team1, team2)); // Benchmark int[] team3 = new int[10]; int[] team4 = new int[10]; for (int i = 0; i < 10; i++) { team3[i] = (int) (Math.floor(Math.random() * 100) + 1); team4[i] = team3[i] + 3; // guarantee a true result, which is worst-case scenario } int N = 1000000; String[] methodsToCompare = {"dumbPhotoShoot", "photoShoot"}; for (String methodName : methodsToCompare) { Class clazz = Class.forName("book.chapter.thirteen.Problem13_06"); Method method = clazz.getDeclaredMethod(methodName, int[].class, int[].class); // Time execution of the reflected method. long startTime = System.nanoTime(); for (int i = 0; i < N; i++) { Boolean retVal = (Boolean) method.invoke(null, team3, team4); if (retVal == false) throw new Exception("wrong result!"); } long endTime = System.nanoTime(); System.out.println( "Elapsed (worst case) time for " + methodName + ": " + (endTime - startTime) / 1000000000.0 + " seconds"); } for (int i = 0; i < 10; i++) { team3[i] = (int) (Math.floor(Math.random() * 100) + 1); team4[i] = team3[i] + 3; } team4[2] = -1; // guarantee a false result on element 2, which is best-case for (String methodName : methodsToCompare) { Class clazz = Class.forName("book.chapter.thirteen.Problem13_06"); Method method = clazz.getDeclaredMethod(methodName, int[].class, int[].class); // Time execution of the reflected method. long startTime = System.nanoTime(); for (int i = 0; i < N; i++) { Boolean retVal = (Boolean) method.invoke(null, team3, team4); if (retVal == true) throw new Exception("wrong result!"); } long endTime = System.nanoTime(); System.out.println( "Elapsed (best case) time for " + methodName + ": " + (endTime - startTime) / 1000000000.0 + " seconds"); } }
@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"); }
/** @see DATACMNS-393 */ @Test public void detectsOverloadedMethodsCorrectly() throws Exception { Class<RepositoryWithAllCrudMethodOverloaded> type = RepositoryWithAllCrudMethodOverloaded.class; assertFindOneMethodOn(type, type.getDeclaredMethod("findOne", Long.class)); assertDeleteMethodOn(type, type.getDeclaredMethod("delete", Long.class)); assertSaveMethodOn(type, type.getDeclaredMethod("save", Domain.class)); assertFindAllMethodOn(type, type.getDeclaredMethod("findAll")); }
public static void botonFinalizar() { // Buscamos si hay una clase hija de BaremacionFAP que implemente un método de // chequeo de condiciones para finalizar la baremacion individual Class invokedClass = null; // Busca una clase que herede de BaremacionFAP List<Class> assignableClasses = Play.classloader.getAssignableClasses(BaremacionFAP.class); if (assignableClasses.size() > 0) { invokedClass = assignableClasses.get(0); } else { invokedClass = BaremacionFAP.class; } if (invokedClass != null) { Method method = null; try { method = invokedClass.getDeclaredMethod("checkFinalizarEvaluacion", Evaluacion.class); } catch (Exception ex) { invokedClass = BaremacionFAP.class; if (invokedClass != null) { method = null; try { method = invokedClass.getDeclaredMethod("checkFinalizarEvaluacion", Evaluacion.class); } catch (Exception e) { play.Logger.error( "Error: No se ha podido encontrar el método checkFinalizarEvaluacion de la clase BaremacionApp"); Messages.error( "Error: No se ha podido ejecutar el método checkFinalizarEvaluacion correctamente"); } } } if (!Messages.hasErrors()) { boolean resultado = false; if (method != null) { try { Long idEvaluacion = Long.parseLong(params.get("idEvaluacion")); Evaluacion evaluacion = Evaluacion.findById(idEvaluacion); resultado = (Boolean) method.invoke(ConsultarEvaluacionesController.class, evaluacion); } catch (Exception e) { play.Logger.error( "Error: No se ha podido invocar el método checkFinalizarEvaluacion de la clase BaremacionFAP"); Messages.error( "Error: No se ha podido ejecutar el metodo checkFinalizarEvaluacion correctamente"); } } else { play.Logger.error( "Error: No existe el Método apropiado para validar checkFinalizarEvaluacion"); Messages.error("Error: No se ha podido ejecutar checkFinalizarEvaluacion correctamente"); } if (!resultado) { play.Logger.error( "Error: La evaluación no cumple las condiciones indicadas en checkFinalizarEvaluacion"); Messages.error( "Error: La evaluación no cumple las condiciones indicadas en checkFinalizarEvaluacion"); } } } }
private RitualType(String cl, String add, String test, Class... args) { try { type = Class.forName(cl); addRitual = type.getDeclaredMethod(add, args); testPlayer = type.getDeclaredMethod(test, EntityPlayer.class); } catch (Exception e) { System.out.println("Could not construct ritual type " + this + "!"); e.printStackTrace(); } }
public static Method getMethod( Class<? extends Object> thisClass, String methodName, Class<?> parameter) throws SecurityException, NoSuchMethodException { Method method = null; if (null == parameter) { method = thisClass.getDeclaredMethod(methodName); } else { method = thisClass.getDeclaredMethod(methodName, parameter); } method.setAccessible(true); return method; }
static GCMParameters extractGcmParameters(AlgorithmParameterSpec paramSpec) throws InvalidParameterSpecException { try { Method tLen = gcmSpecClass.getDeclaredMethod("getTLen", new Class[0]); Method iv = gcmSpecClass.getDeclaredMethod("getIV", new Class[0]); return new GCMParameters( (byte[]) iv.invoke(paramSpec, new Object[0]), ((Integer) tLen.invoke(paramSpec, new Object[0])).intValue() / 8); } catch (Exception e) { throw new InvalidParameterSpecException("Cannot process GCMParameterSpec"); } }
private static void init() { try { if (mClassType == null) { mClassType = Class.forName("android.os.SystemProperties"); mGetMethod = mClassType.getDeclaredMethod("get", String.class); mGetIntMethod = mClassType.getDeclaredMethod("getInt", String.class, int.class); mGetBooleanMethod = mClassType.getDeclaredMethod("getBoolean", String.class, boolean.class); } } catch (Exception e) { e.printStackTrace(); } }
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(); } }
/* * Locates the Java methods for calling methods on {@code MethodType} instances, if those are available. */ static { JavaMethod returnType, parameterArray; try { Class<?> methodType = JavaType.METHOD_TYPE.load(); returnType = new JavaMethod.ForLoadedMethod(methodType.getDeclaredMethod("returnType")); parameterArray = new JavaMethod.ForLoadedMethod(methodType.getDeclaredMethod("parameterArray")); } catch (Exception ignored) { returnType = JavaMethod.ForUnavailableMethod.INSTANCE; parameterArray = JavaMethod.ForUnavailableMethod.INSTANCE; } RETURN_TYPE = returnType; PARAMETER_ARRAY = parameterArray; }
public static void loadAgent(Path agent) throws Exception { String vmName = ManagementFactory.getRuntimeMXBean().getName(); int p = vmName.indexOf('@'); assumeTrue(p != -1); String pid = vmName.substring(0, p); ClassLoader cl = ToolProvider.getSystemToolClassLoader(); Class<?> c = Class.forName("com.sun.tools.attach.VirtualMachine", true, cl); Method attach = c.getDeclaredMethod("attach", String.class); Method loadAgent = c.getDeclaredMethod("loadAgent", String.class, String.class); Method detach = c.getDeclaredMethod("detach"); Object vm = attach.invoke(null, pid); loadAgent.invoke(vm, agent.toString(), ""); detach.invoke(vm); }
public static void checkShapesImplementEquals(Class[] classes) { for (Class clazz : classes) { try { clazz.getDeclaredMethod("equals", Object.class); } catch (Exception e) { fail("Shape needs to define 'equals' : " + clazz.getName()); } try { clazz.getDeclaredMethod("hashCode"); } catch (Exception e) { fail("Shape needs to define 'hashCode' : " + clazz.getName()); } } }
private boolean evaluateConditions(Logger LOG, Injector injector, Module module) throws Exception { LOG.info("Evaluating module {}", module.getClass().getName()); // The class may have multiple Conditional annotations for (Annotation annot : module.getClass().getAnnotations()) { Conditional conditional = annot.annotationType().getAnnotation(Conditional.class); if (conditional != null) { // A Conditional may have a list of multiple Conditions for (Class<? extends Condition> condition : conditional.value()) { try { // Construct the condition using Guice so that anything may be injected into // the condition Condition c = injector.getInstance(condition); // Look for method signature : boolean check(T annot) // where T is the annotation type. Note that the same checker will be used // for all conditions of the same annotation type. try { Method check = condition.getDeclaredMethod("check", annot.annotationType()); if (!(boolean) check.invoke(c, annot)) { LOG.info(" - {}", formatConditional(annot)); return false; } } // If not found, look for method signature // boolean check(); catch (NoSuchMethodException e) { Method check = condition.getDeclaredMethod("check"); if (!(boolean) check.invoke(c)) { LOG.info(" - {}", formatConditional(annot)); return false; } } LOG.info(" + {}", formatConditional(annot)); } catch (Exception e) { LOG.info(" - {}", formatConditional(annot)); throw new Exception( "Failed to check condition '" + condition + "' on module '" + module.getClass() + "'"); } } } } return true; }