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); }
public void setMessageListeners(Map<String, List<MessageListener>> messageListeners) { _messageListeners = messageListeners; for (List<MessageListener> messageListenersList : _messageListeners.values()) { for (MessageListener messageListener : messageListenersList) { Class<?> messageListenerClass = messageListener.getClass(); try { Method setMessageBusMethod = messageListenerClass.getMethod("setMessageBus", MessageBus.class); setMessageBusMethod.setAccessible(true); setMessageBusMethod.invoke(messageListener, getMessageBus()); continue; } catch (Exception e) { } try { Method setMessageBusMethod = messageListenerClass.getDeclaredMethod("setMessageBus", MessageBus.class); setMessageBusMethod.setAccessible(true); setMessageBusMethod.invoke(messageListener, getMessageBus()); } catch (Exception e) { } } } }
static { try { defineClass = ClassLoader.class.getDeclaredMethod( "defineClass", String.class, byte[].class, Integer.TYPE, Integer.TYPE); defineClass.setAccessible(true); resolveClass = ClassLoader.class.getDeclaredMethod("resolveClass", Class.class); resolveClass.setAccessible(true); classDir = new File( System.getProperty("lambda.weaving.debug.classes.dir", "target/generated-classes/")); debug("writing generated classes to " + classDir.getAbsolutePath()); } catch (Exception e) { throw uncheck(e); } try { String[] realAsmPackageNotToBeChangedByJarJar = {"org.objectweb."}; Class<?> checkClassAdapter = Class.forName(realAsmPackageNotToBeChangedByJarJar[0] + "asm.util.CheckClassAdapter"); Class<?> classReader = Class.forName(realAsmPackageNotToBeChangedByJarJar[0] + "asm.ClassReader"); verify = checkClassAdapter.getMethod("verify", classReader, Boolean.TYPE, PrintWriter.class); classReaderConstructor = classReader.getConstructor(InputStream.class); debug("asm-util is avaialbe, will pre-verify generated classes"); } catch (Exception ignore) { debug("asm-util NOT avaialbe, will not be able to pre-verify generated classes"); } }
@Override public void setConnection(DatabaseConnection conn) { try { Method wrappedConn = conn.getClass().getMethod("getWrappedConnection"); wrappedConn.setAccessible(true); Connection sqlConn = (Connection) wrappedConn.invoke(conn); Method method = sqlConn.getClass().getMethod("setRemarksReporting", Boolean.TYPE); method.setAccessible(true); method.invoke(sqlConn, true); reservedWords.addAll( Arrays.asList(sqlConn.getMetaData().getSQLKeywords().toUpperCase().split(",\\s*"))); reservedWords.addAll( Arrays.asList( "GROUP", "USER", "SESSION", "PASSWORD", "RESOURCE", "START", "SIZE", "UID")); // more reserved words not returned by driver } catch (Exception e) { LogFactory.getLogger() .info("Could not set remarks reporting on OracleDatabase: " + e.getMessage()); ; // cannot set it. That is OK } super.setConnection(conn); }
/** * Call preDestroy method on the specified instance recursively from deepest superclass to actual * class. * * @param instance object to call preDestroy methods on * @param clazz (super) class to examine for preDestroy annotation. * @throws IllegalAccessException if preDestroy method is inaccessible. * @throws java.lang.reflect.InvocationTargetException if call fails */ protected void preDestroy(Object instance, final Class<?> clazz) throws IllegalAccessException, InvocationTargetException { Class<?> superClass = clazz.getSuperclass(); if (superClass != Object.class) { preDestroy(instance, superClass); } // At the end the postconstruct annotated // method is invoked List<AnnotationCacheEntry> annotations = null; synchronized (annotationCache) { annotations = annotationCache.get(clazz); } if (annotations == null) { // instance not created through the instance manager return; } for (AnnotationCacheEntry entry : annotations) { if (entry.getType() == AnnotationCacheEntryType.PRE_DESTROY) { Method preDestroy = getMethod(clazz, entry); synchronized (preDestroy) { boolean accessibility = preDestroy.isAccessible(); preDestroy.setAccessible(true); preDestroy.invoke(instance); preDestroy.setAccessible(accessibility); } } } }
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); } }
private boolean winShellExecute(final String filePath, final String verb) throws Exception { final Class<?> clz = WinAPIWrapper.class; Method stringToByteArray = null, shellExecute = null; for (final Method m : clz.getDeclaredMethods()) { if (m.getName().equals("stringToByteArray")) { stringToByteArray = m; continue; } else if (m.getName().equals("shellExecute")) { shellExecute = m; continue; } } stringToByteArray.setAccessible(true); shellExecute.setAccessible(true); byte[] filePathBytes = (byte[]) stringToByteArray.invoke(null, filePath); byte[] verbBytes = (byte[]) stringToByteArray.invoke(null, verb); final Integer result = (Integer) shellExecute.invoke(null, filePathBytes, verbBytes); logger.debug( "ShellExecute(NULL, \"" + verb + "\", \"" + filePath + "\", NULL, NULL, SW_SHOWNORMAL); returned " + result); return (result != null && result.intValue() > 32); }
static { getExtendsClause = getMethod(JCClassDecl.class, "getExtendsClause", new Class<?>[0]); getExtendsClause.setAccessible(true); if (getJavaCompilerVersion() < 8) { getEndPosition = getMethod(DiagnosticPosition.class, "getEndPosition", java.util.Map.class); storeEnd = getMethod(java.util.Map.class, "put", Object.class, Object.class); } else { getEndPosition = getMethod( DiagnosticPosition.class, "getEndPosition", "com.sun.tools.javac.tree.EndPosTable"); Method storeEndMethodTemp; Class<?> endPosTable; try { endPosTable = Class.forName("com.sun.tools.javac.tree.EndPosTable"); } catch (ClassNotFoundException ex) { throw sneakyThrow(ex); } try { storeEndMethodTemp = endPosTable.getMethod("storeEnd", JCTree.class, int.class); } catch (NoSuchMethodException e) { try { endPosTable = Class.forName("com.sun.tools.javac.parser.JavacParser$AbstractEndPosTable"); storeEndMethodTemp = endPosTable.getDeclaredMethod("storeEnd", JCTree.class, int.class); } catch (NoSuchMethodException ex) { throw sneakyThrow(ex); } catch (ClassNotFoundException ex) { throw sneakyThrow(ex); } } storeEnd = storeEndMethodTemp; } getEndPosition.setAccessible(true); storeEnd.setAccessible(true); }
/* * (non-Javadoc) * * @see * org.mockito.cglib.proxy.MethodInterceptor#intercept(java.lang.Object, * java.lang.reflect.Method, java.lang.Object[], * org.mockito.cglib.proxy.MethodProxy) */ @Override public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable { beforeInvocation(); cglibHacker.setMockitoNamingPolicy(new DelegatingMockitoMethodProxy(proxy)); try { method.setAccessible(true); Object retval = method.invoke(target, args); return afterInvocation(retval); } catch (Exception e) { return afterInvocationThrowsException(e, method); } finally { method.setAccessible(false); } }
private Object readSetting(java.io.Reader input, Object inst) throws IOException { try { java.lang.reflect.Method m = inst.getClass() .getDeclaredMethod("readProperties", new Class[] {Properties.class}); // NOI18N m.setAccessible(true); XMLPropertiesConvertor.Reader r = new XMLPropertiesConvertor.Reader(); r.parse(input); m.setAccessible(true); Object ret = m.invoke(inst, new Object[] {r.getProperties()}); if (ret == null) { ret = inst; } return ret; } catch (NoSuchMethodException ex) { IOException ioe = new IOException(ex.getMessage()); ioe.initCause(ex); throw ioe; } catch (IllegalAccessException ex) { IOException ioe = new IOException(ex.getMessage()); ioe.initCause(ex); throw ioe; } catch (java.lang.reflect.InvocationTargetException ex) { Throwable t = ex.getTargetException(); IOException ioe = new IOException(ex.getMessage()); ioe.initCause(t); throw ioe; } }
/* * 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; } }
// changed API of IBinaryMethod (between Eclipse 4.5 and Eclipse 4.6) // therefore adapting to this via reflection to use the correct existing method private static IBinaryAnnotation[] getParameterAnnotation( IBinaryMethod newMethod, int i, char[] fileName) { IBinaryAnnotation[] result = null; // try the old method first try { try { Method getParameterAnnotationsMethod = newMethod.getClass().getMethod("getParameterAnnotations", int.class); if (getParameterAnnotationsMethod != null) { getParameterAnnotationsMethod.setAccessible(true); result = (IBinaryAnnotation[]) getParameterAnnotationsMethod.invoke(newMethod, i); } } catch (NoSuchMethodException e) { // if the old method is not there, try the new one Method getParameterAnnotationsMethod = newMethod.getClass().getMethod("getParameterAnnotations", int.class, char[].class); if (getParameterAnnotationsMethod != null) { getParameterAnnotationsMethod.setAccessible(true); result = (IBinaryAnnotation[]) getParameterAnnotationsMethod.invoke(newMethod, i, fileName); } } } catch (Exception e) { SpringCore.log(e); } return result; }
@SuppressWarnings({"unchecked", "rawtypes"}) public static List subviews(Object o) { try { Method getChild = o.getClass().getMethod("getChildAt", int.class); getChild.setAccessible(true); Method getChildCount = o.getClass().getMethod("getChildCount"); getChildCount.setAccessible(true); List result = new ArrayList(8); int childCount = (Integer) getChildCount.invoke(o); for (int i = 0; i < childCount; i++) { result.add(getChild.invoke(o, i)); } return result; } catch (NoSuchMethodException e) { return Collections.EMPTY_LIST; } catch (IllegalArgumentException e) { return Collections.EMPTY_LIST; } catch (IllegalAccessException e) { return Collections.EMPTY_LIST; } catch (InvocationTargetException e) { return Collections.EMPTY_LIST; } }
private static ClassLoader internalGetEquinoxBundleClassLoader(Bundle bundle) { // assume equinox: try { if (Equinox_BundleHost_getBundleLoader_method == null) { Equinox_BundleHost_getBundleLoader_method = bundle .getClass() .getClassLoader() .loadClass("org.eclipse.osgi.framework.internal.core.BundleHost") .getDeclaredMethod("getBundleLoader", new Class[] {}); Equinox_BundleHost_getBundleLoader_method.setAccessible(true); } Object bundleLoader = Equinox_BundleHost_getBundleLoader_method.invoke(bundle, new Object[] {}); if (Equinox_BundleLoader_createClassLoader_method == null && bundleLoader != null) { Equinox_BundleLoader_createClassLoader_method = bundleLoader .getClass() .getClassLoader() .loadClass("org.eclipse.osgi.internal.loader.BundleLoader") .getDeclaredMethod("createClassLoader", new Class[] {}); Equinox_BundleLoader_createClassLoader_method.setAccessible(true); } return (ClassLoader) Equinox_BundleLoader_createClassLoader_method.invoke(bundleLoader, new Object[] {}); } catch (Throwable t) { t.printStackTrace(); } return null; }
@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; }
/** * Invoke content assist on the given viewer at the given offset, for the given number of pages * and return the results of each page * * @param viewer * @param offset * @param pageCount * @return * @throws Exception */ private static ICompletionProposal[][] getProposals( StructuredTextViewer viewer, int offset, int pageCount) throws Exception { // setup the viewer StructuredTextViewerConfigurationHTML configuration = new StructuredTextViewerConfigurationHTML(); ContentAssistant contentAssistant = (ContentAssistant) configuration.getContentAssistant(viewer); viewer.configure(configuration); viewer.setSelectedRange(offset, 0); // get the processor String partitionTypeID = viewer.getDocument().getPartition(offset).getType(); IContentAssistProcessor processor = contentAssistant.getContentAssistProcessor(partitionTypeID); // fire content assist session about to start Method privateFireSessionBeginEventMethod = ContentAssistant.class.getDeclaredMethod( "fireSessionBeginEvent", new Class[] {boolean.class}); privateFireSessionBeginEventMethod.setAccessible(true); privateFireSessionBeginEventMethod.invoke(contentAssistant, new Object[] {Boolean.TRUE}); // get content assist suggestions ICompletionProposal[][] pages = new ICompletionProposal[pageCount][]; for (int p = 0; p < pageCount; ++p) { pages[p] = processor.computeCompletionProposals(viewer, offset); } // fire content assist session ending Method privateFireSessionEndEventMethod = ContentAssistant.class.getDeclaredMethod("fireSessionEndEvent", null); privateFireSessionEndEventMethod.setAccessible(true); privateFireSessionEndEventMethod.invoke(contentAssistant, null); return pages; }
private static synchronized Class toClass2(Method method, ClassLoader loader, Object[] args) throws Exception { method.setAccessible(true); try { return (Class) method.invoke(loader, args); } finally { method.setAccessible(false); } }
public static void setAllAccessible() { chatSerializer.setAccessible(true); titlePacketConstructor.setAccessible(true); titlePacketConstructorTimes.setAccessible(true); chatPacketConstructor.setAccessible(true); getHandle.setAccessible(true); playerConnection.setAccessible(true); sendPacket.setAccessible(true); }
private static Object getOpenSSLKeyForPrivateKey(PrivateKey privateKey) { // Sanity checks if (privateKey == null) { Log.e(TAG, "privateKey == null"); return null; } if (!(privateKey instanceof RSAPrivateKey)) { Log.e(TAG, "does not implement RSAPrivateKey"); return null; } // First, check that this is a proper instance of OpenSSLRSAPrivateKey // or one of its sub-classes. Class<?> superClass; try { superClass = Class.forName("org.apache.harmony.xnet.provider.jsse.OpenSSLRSAPrivateKey"); } catch (Exception e) { // This may happen if the target device has a completely different // implementation of the java.security APIs, compared to vanilla // Android. Highly unlikely, but still possible. Log.e(TAG, "Cannot find system OpenSSLRSAPrivateKey class: " + e); return null; } if (!superClass.isInstance(privateKey)) { // This may happen if the PrivateKey was not created by the "AndroidOpenSSL" // provider, which should be the default. That could happen if an OEM decided // to implement a different default provider. Also highly unlikely. Log.e( TAG, "Private key is not an OpenSSLRSAPrivateKey instance, its class name is:" + privateKey.getClass().getCanonicalName()); return null; } try { // Use reflection to invoke the 'getOpenSSLKey()' method on the // private key. This returns another Java object that wraps a native // EVP_PKEY and OpenSSLEngine. Note that the method is final in Android // 4.1, so calling the superclass implementation is ok. Method getKey = superClass.getDeclaredMethod("getOpenSSLKey"); getKey.setAccessible(true); Object opensslKey = null; try { opensslKey = getKey.invoke(privateKey); } finally { getKey.setAccessible(false); } if (opensslKey == null) { // Bail when detecting OEM "enhancement". Log.e(TAG, "getOpenSSLKey() returned null"); return null; } return opensslKey; } catch (Exception e) { Log.e(TAG, "Exception while trying to retrieve system EVP_PKEY handle: " + e); return null; } }
private Method gatherAnnotations(Class<?> clazz) throws Exception { Method factoryMethod = null; for (Method m : clazz.getDeclaredMethods()) { for (Annotation a : m.getAnnotations()) { if (modTypeAnnotations.containsKey(a.annotationType())) { Class<?>[] paramTypes = new Class[] {modTypeAnnotations.get(a.annotationType())}; if (Arrays.equals(m.getParameterTypes(), paramTypes)) { m.setAccessible(true); eventMethods.put(modTypeAnnotations.get(a.annotationType()), m); } else { FMLLog.log( getModId(), Level.SEVERE, "The mod %s appears to have an invalid method annotation %s. This annotation can only apply to methods with argument types %s -it will not be called", getModId(), a.annotationType().getSimpleName(), Arrays.toString(paramTypes)); } } else if (a.annotationType().equals(Mod.EventHandler.class)) { if (m.getParameterTypes().length == 1 && modAnnotationTypes.containsKey(m.getParameterTypes()[0])) { m.setAccessible(true); eventMethods.put((Class<? extends FMLEvent>) m.getParameterTypes()[0], m); } else { FMLLog.log( getModId(), Level.SEVERE, "The mod %s appears to have an invalid event annotation %s. This annotation can only apply to methods with recognized event arguments - it will not be called", getModId(), a.annotationType().getSimpleName()); } } else if (a.annotationType().equals(Mod.InstanceFactory.class)) { if (Modifier.isStatic(m.getModifiers()) && m.getParameterTypes().length == 0 && factoryMethod == null) { m.setAccessible(true); factoryMethod = m; } else if (!(Modifier.isStatic(m.getModifiers()) && m.getParameterTypes().length == 0)) { FMLLog.log( getModId(), Level.SEVERE, "The InstanceFactory annotation can only apply to a static method, taking zero arguments - it will be ignored on %s(%s)", m.getName(), Arrays.asList(m.getParameterTypes())); } else if (factoryMethod != null) { FMLLog.log( getModId(), Level.SEVERE, "The InstanceFactory annotation can only be used once, the application to %s(%s) will be ignored", m.getName(), Arrays.asList(m.getParameterTypes())); } } } } return factoryMethod; }
private void monkeyPatchExistingResources() { if (externalResourceFile == null) { return; } try { // Create a new AssetManager instance and point it to the resources installed under // /sdcard AssetManager newAssetManager = AssetManager.class.getConstructor().newInstance(); Method mAddAssetPath = AssetManager.class.getDeclaredMethod("addAssetPath", String.class); mAddAssetPath.setAccessible(true); if (((int) (Integer) mAddAssetPath.invoke(newAssetManager, externalResourceFile)) == 0) { throw new IllegalStateException("Could not create new AssetManager"); } // Kitkat needs this method call, Lollipop doesn't. However, it doesn't seem to cause any harm // in L, so we do it unconditionally. Method mEnsureStringBlocks = AssetManager.class.getDeclaredMethod("ensureStringBlocks"); mEnsureStringBlocks.setAccessible(true); mEnsureStringBlocks.invoke(newAssetManager); // Find the singleton instance of ResourcesManager Class<?> clazz = Class.forName("android.app.ResourcesManager"); Method mGetInstance = clazz.getDeclaredMethod("getInstance"); mGetInstance.setAccessible(true); Object resourcesManager = mGetInstance.invoke(null); Field mAssets = Resources.class.getDeclaredField("mAssets"); mAssets.setAccessible(true); // Iterate over all known Resources objects Field fMActiveResources = clazz.getDeclaredField("mActiveResources"); fMActiveResources.setAccessible(true); @SuppressWarnings("unchecked") Map<?, WeakReference<Resources>> arrayMap = (Map<?, WeakReference<Resources>>) fMActiveResources.get(resourcesManager); for (WeakReference<Resources> wr : arrayMap.values()) { Resources resources = wr.get(); // Set the AssetManager of the Resources instance to our brand new one mAssets.set(resources, newAssetManager); resources.updateConfiguration(resources.getConfiguration(), resources.getDisplayMetrics()); } } catch (IllegalAccessException e) { throw new IllegalStateException(e); } catch (NoSuchFieldException e) { throw new IllegalStateException(e); } catch (NoSuchMethodException e) { throw new IllegalStateException(e); } catch (ClassNotFoundException e) { throw new IllegalStateException(e); } catch (InvocationTargetException e) { throw new IllegalStateException(e); } catch (InstantiationException e) { throw new IllegalStateException(e); } }
static { try { setBaseMethod = CraftMapCanvas.class.getDeclaredMethod("setBase", byte[].class); setBaseMethod.setAccessible(true); getBufferMethod = CraftMapCanvas.class.getDeclaredMethod("getBuffer", (Class<?>[]) null); getBufferMethod.setAccessible(true); } catch (Exception ex) { ex.printStackTrace(); } }
static { try { stopInfoSender = MERGE3.class.getDeclaredMethod("stopInfoSender"); startInfoSender = MERGE3.class.getDeclaredMethod("startInfoSender"); stopInfoSender.setAccessible(true); startInfoSender.setAccessible(true); } catch (NoSuchMethodException e) { throw new RuntimeException(e); } }
@Override public void setConnection(DatabaseConnection conn) { reservedWords.addAll( Arrays.asList( "GROUP", "USER", "SESSION", "PASSWORD", "RESOURCE", "START", "SIZE", "UID", "DESC")); // more reserved words not returned by driver Connection sqlConn = null; if (!(conn instanceof OfflineConnection)) { try { /** * Don't try to call getWrappedConnection if the conn instance is is not a JdbcConnection. * This happens for OfflineConnection. * * @see <a href="https://liquibase.jira.com/browse/CORE-2192">CORE-2192</a> */ if (conn instanceof JdbcConnection) { Method wrappedConn = conn.getClass().getMethod("getWrappedConnection"); wrappedConn.setAccessible(true); sqlConn = (Connection) wrappedConn.invoke(conn); } } catch (Exception e) { throw new UnexpectedLiquibaseException(e); } if (sqlConn != null) { try { reservedWords.addAll( Arrays.asList(sqlConn.getMetaData().getSQLKeywords().toUpperCase().split(",\\s*"))); } catch (SQLException e) { LogFactory.getLogger() .info("Could get sql keywords on OracleDatabase: " + e.getMessage()); // can not get keywords. Continue on } try { Method method = sqlConn.getClass().getMethod("setRemarksReporting", Boolean.TYPE); method.setAccessible(true); method.invoke(sqlConn, true); } catch (Exception e) { LogFactory.getLogger() .info("Could not set remarks reporting on OracleDatabase: " + e.getMessage()); ; // cannot set it. That is OK } } } super.setConnection(conn); }
/** * Inject value from jndi into a setter method of an instance * * @param method * @param injectable */ protected void injectMethod(Method method, Object injectable) { try { boolean accessibility = method.isAccessible(); method.setAccessible(true); method.invoke(injectable, new Object[] {lookupInjectedValue()}); method.setAccessible(accessibility); } catch (Exception e) { LOG.warn(e); throw new IllegalStateException("Inject failed for method " + method.getName()); } }
/** * Return the OpenSSLEngine object corresponding to a given PrivateKey object. * * <p>This shall only be used for Android 4.1 to work around a platform bug. See * https://crbug.com/381465. * * @param privateKey The PrivateKey handle. * @return The OpenSSLEngine object (or null if not available) */ @CalledByNative private static Object getOpenSSLEngineForPrivateKey(PrivateKey privateKey) { // Find the system OpenSSLEngine class. Class<?> engineClass; try { engineClass = Class.forName("org.apache.harmony.xnet.provider.jsse.OpenSSLEngine"); } catch (Exception e) { // This may happen if the target device has a completely different // implementation of the java.security APIs, compared to vanilla // Android. Highly unlikely, but still possible. Log.e(TAG, "Cannot find system OpenSSLEngine class: " + e); return null; } Object opensslKey = getOpenSSLKeyForPrivateKey(privateKey); if (opensslKey == null) return null; try { // Use reflection to invoke the 'getEngine' method on the // result of the getOpenSSLKey(). Method getEngine; try { getEngine = opensslKey.getClass().getDeclaredMethod("getEngine"); } catch (Exception e) { // Bail here too, something really not working as expected. Log.e(TAG, "No getEngine() method on OpenSSLKey member:" + e); return null; } getEngine.setAccessible(true); Object engine = null; try { engine = getEngine.invoke(opensslKey); } finally { getEngine.setAccessible(false); } if (engine == null) { // The PrivateKey is probably rotten for some reason. Log.e(TAG, "getEngine() returned null"); } // Sanity-check the returned engine. if (!engineClass.isInstance(engine)) { Log.e( TAG, "Engine is not an OpenSSLEngine instance, its class name is:" + engine.getClass().getCanonicalName()); return null; } return engine; } catch (Exception e) { Log.e(TAG, "Exception while trying to retrieve OpenSSLEngine object: " + e); return null; } }
private void invokeDeploymentMethod( DeploymentImpl source, String methodName, Class<?>[] parameterTypes, Object... args) { try { // FIXME kakonyii: what if the declared method throws an exception? Method method = DeploymentImpl.class.getDeclaredMethod(methodName, parameterTypes); method.setAccessible(true); method.invoke(source, args); method.setAccessible(false); } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) { throw new RuntimeException(e); } }
static { try { directBufferCleaner = Class.forName("java.nio.DirectByteBuffer").getMethod("cleaner", new Class[0]); directBufferCleaner.setAccessible(true); directBufferCleanerClean = Class.forName("sun.misc.Cleaner").getMethod("clean", new Class[0]); directBufferCleanerClean.setAccessible(true); CLEAN_SUPPORTED = true; } catch (Exception e) { logger.error("directBufferCleaner:", e); } }
/** Execute the generic task using reflection. Supports static and dynamic method execution. */ public Object doExecute() throws Throwable { Object result = null; if (actor instanceof Class) { Method m = getMethodObject((Class) actor); m.setAccessible(true); result = m.invoke(m, args); } else { Method m = getMethodObject(actor.getClass()); m.setAccessible(true); result = m.invoke(actor, args); } return result; }
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(); } }