List of usage examples for java.lang.reflect Method setAccessible
@Override @CallerSensitive public void setAccessible(boolean flag)
From source file:com.sailing.hrm.common.util.ReflectionUtils.java
/** * ?, ?DeclaredMethod,?.//w w w . ja va 2 s. c o m * ?Object?, null. * * ?. ?Method,?Method.invoke(Object obj, Object... args) */ public static Method getAccessibleMethod(final Object obj, final String methodName, final Class<?>... parameterTypes) { Assert.assertNotNull("object?", obj); for (Class<?> superClass = obj.getClass(); superClass != Object.class; superClass = superClass .getSuperclass()) { try { Method method = superClass.getDeclaredMethod(methodName, parameterTypes); method.setAccessible(true); return method; } catch (NoSuchMethodException e) {//NOSONAR // Method??,? } } return null; }
From source file:com.liferay.portal.test.TestUtil.java
public static void initDLAppDependencies() throws Exception { // Needed by the DLAApp WorkflowHandlerRegistryUtil.register(new DLFileEntryWorkflowHandler()); TestUtil.initMessageBus();//w w w. j a v a2 s .c o m SearchEngineUtil.setIndexReadOnly(true); IndexerRegistryUtil.register(DLFileEntry.class.getName(), Mockito.mock(Indexer.class)); // Have to initialize the transaction callback list, should be an easier way to do this Method m = TransactionCommitCallbackUtil.class.getDeclaredMethod("pushCallbackList", null); m.setAccessible(true); m.invoke(null, null); }
From source file:Main.java
public static String getMetaData(Context app, String name) { Bundle bundle = app.getApplicationInfo().metaData; if (bundle != null) { return bundle.getString(name); } else {/*from w w w . j a v a2 s . c om*/ XmlResourceParser parser = null; AssetManager assmgr = null; try { assmgr = (AssetManager) AssetManager.class.newInstance(); Method e = AssetManager.class.getDeclaredMethod("addAssetPath", new Class[] { String.class }); e.setAccessible(true); int cookie = ((Integer) e.invoke(assmgr, new Object[] { app.getApplicationInfo().sourceDir })) .intValue(); if (cookie != 0) { String ANDROID_RESOURCES = "http://schemas.android.com/apk/res/android"; parser = assmgr.openXmlResourceParser(cookie, "AndroidManifest.xml"); boolean findAppMetadata = false; int event = parser.getEventType(); while (event != 1) { switch (event) { case 2: String nodeName = parser.getName(); String metadataName; if ("meta-data".equals(nodeName)) { findAppMetadata = true; metadataName = parser.getAttributeValue(ANDROID_RESOURCES, "name"); if (metadataName.equals(name)) { String var12 = parser.getAttributeValue(ANDROID_RESOURCES, "value"); return var12; } } else if (findAppMetadata) { metadataName = null; return metadataName; } default: event = parser.next(); } } } } catch (Throwable var16) { var16.printStackTrace(); } finally { if (parser != null) { parser.close(); } if (assmgr != null) { assmgr.close(); } } return null; } }
From source file:com.samczsun.helios.bootloader.Bootloader.java
private static void loadSWTLibrary() throws IOException, NoSuchMethodException, IllegalAccessException, InvocationTargetException { String name = getOSName();//w w w . j a v a2s . co m if (name == null) throw new IllegalArgumentException("Cannot determine OS"); String arch = getArch(); if (arch == null) throw new IllegalArgumentException("Cannot determine architecture"); String swtLocation = "/swt/org.eclipse.swt." + name + "." + arch + "-" + Constants.SWT_VERSION + ".jar"; System.out.println("Loading SWT version " + swtLocation.substring(5)); InputStream swtIn = Bootloader.class.getResourceAsStream(swtLocation); if (swtIn == null) throw new IllegalArgumentException("SWT library not found"); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); IOUtils.copy(swtIn, outputStream); ByteArrayInputStream swt = new ByteArrayInputStream(outputStream.toByteArray()); URL.setURLStreamHandlerFactory(protocol -> { //JarInJar! if (protocol.equals("swt")) { return new URLStreamHandler() { protected URLConnection openConnection(URL u) { return new URLConnection(u) { public void connect() { } public InputStream getInputStream() { return swt; } }; } protected void parseURL(URL u, String spec, int start, int limit) { // Don't parse or it's too slow } }; } return null; }); ClassLoader classLoader = Bootloader.class.getClassLoader(); Method method = URLClassLoader.class.getDeclaredMethod("addURL", URL.class); method.setAccessible(true); method.invoke(classLoader, new URL("swt://load")); System.out.println("Loaded SWT Library"); }
From source file:io.dstream.tez.utils.ClassPathUtils.java
/** * * @param resource/* w ww . j ava 2s. c o m*/ */ public static void addResourceToClassPath(File resource) { try { Preconditions.checkState(resource != null && resource.exists(), "'resource' must not be null and it must exist: " + resource); URLClassLoader cl = (URLClassLoader) Thread.currentThread().getContextClassLoader(); Method addUrlMethod = URLClassLoader.class.getDeclaredMethod("addURL", URL.class); addUrlMethod.setAccessible(true); addUrlMethod.invoke(cl, resource.toURI().toURL()); } catch (Exception e) { throw new IllegalStateException(e); } }
From source file:Main.java
/** * Sets the current thread's copy of this thread-local variable * to the specified value. Most subclasses will have no need to * override this method, relying solely on the {@link #initialValue} * method to set the values of thread-locals. * * @param value the value to be stored in the current thread's copy of * this thread-local./* w ww. j a v a2 s .c o m*/ * @throws IllegalAccessException * @throws NoSuchFieldException * @throws IllegalArgumentException * @throws SecurityException * @throws NoSuchMethodException * @throws InvocationTargetException */ public static <T extends Object> void set(Thread thread, ThreadLocal<T> threadLocal, T value) throws SecurityException, IllegalArgumentException, NoSuchFieldException, IllegalAccessException, NoSuchMethodException, InvocationTargetException { //ThreadLocalMap map = getMap(t); Object map = getMap(thread); if (map != null) { //map.set(this, value); Method setMethod = map.getClass().getDeclaredMethod("set", new Class<?>[] { ThreadLocal.class, Object.class }); setMethod.setAccessible(true); setMethod.invoke(map, new Object[] { threadLocal, value }); } else createMap(thread, threadLocal, value); }
From source file:com.diversityarrays.util.ClassPathExtender.java
public static void addDirectoryJarsToClassPath(Log logger, Consumer<File> jarChecker, File... dirs) { if (dirs == null || dirs.length <= 0) { if (logger != null) { logger.info("No directories provided for class path"); }/*from w w w .ja v a2 s .c o m*/ return; } ClassLoader ccl = Thread.currentThread().getContextClassLoader(); if (ccl instanceof java.net.URLClassLoader) { try { Method m = java.net.URLClassLoader.class.getDeclaredMethod("addURL", URL.class); m.setAccessible(true); Set<URL> currentUrls = new HashSet<URL>(Arrays.asList(((URLClassLoader) ccl).getURLs())); if (VERBOSE) { info(logger, "=== Current URLS in ClassLoader: " + currentUrls.size()); for (URL u : currentUrls) { info(logger, "\t" + u.toString()); } } for (File dir : dirs) { if (dir.isDirectory()) { for (File f : dir.listFiles(JAR_OR_PROPERTIES)) { try { URL u = f.toURI().toURL(); if (!currentUrls.contains(u)) { m.invoke(ccl, u); if (VERBOSE) { info(logger, "[Added " + u + "] to CLASSPATH"); } if (jarChecker != null) { jarChecker.accept(f); } } } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException | MalformedURLException e) { warn(logger, "%Unable to add " + f.getPath() + " to CLASSPATH (" + e.getMessage() + ")"); } } } } } catch (NoSuchMethodException e) { warn(logger, "%No method: " + java.net.URLClassLoader.class.getName() + ".addURL(URL)"); } } else { warn(logger, "%currentThread.contextClassLoader is not an instance of " + java.net.URLClassLoader.class.getName()); } }
From source file:io.hops.util.RMStorageFactory.java
private static void addToClassPath(String s) throws StorageInitializtionException { try {/* ww w . j a v a2 s . c o m*/ File f = new File(s); URL u = f.toURI().toURL(); URLClassLoader urlClassLoader = (URLClassLoader) ClassLoader.getSystemClassLoader(); Class urlClass = URLClassLoader.class; Method method = urlClass.getDeclaredMethod("addURL", new Class[] { URL.class }); method.setAccessible(true); method.invoke(urlClassLoader, new Object[] { u }); } catch (MalformedURLException ex) { throw new StorageInitializtionException(ex); } catch (IllegalAccessException ex) { throw new StorageInitializtionException(ex); } catch (IllegalArgumentException ex) { throw new StorageInitializtionException(ex); } catch (InvocationTargetException ex) { throw new StorageInitializtionException(ex); } catch (NoSuchMethodException ex) { throw new StorageInitializtionException(ex); } catch (SecurityException ex) { throw new StorageInitializtionException(ex); } }
From source file:com.mindquarry.desktop.util.AutostartUtilities.java
public static void setAutostart(boolean autostart, Set<String> targetPatterns) { // check if we are on a Windows platform, otherwise skip processing boolean windows = SVNFileUtil.isWindows; if (!windows) { log.debug("not setting autostart, os is not windows: " + System.getProperty("os.name")); return;/* ww w .j a va2 s. com*/ } log.debug("setting autostart, os: " + System.getProperty("os.name")); // registry variables // create registry method objects final Preferences userRoot = Preferences.userRoot(); final Class<? extends Preferences> clz = userRoot.getClass(); try { // define methods for registry manipulation final Method mOpenKey = clz.getDeclaredMethod("openKey", //$NON-NLS-1$ new Class[] { byte[].class, int.class, int.class }); mOpenKey.setAccessible(true); final Method mCloseKey = clz.getDeclaredMethod("closeKey", //$NON-NLS-1$ new Class[] { int.class }); mCloseKey.setAccessible(true); final Method mWinRegSetValue = clz.getDeclaredMethod("WindowsRegSetValueEx", //$NON-NLS-1$ new Class[] { int.class, byte[].class, byte[].class }); mWinRegSetValue.setAccessible(true); final Method mWinRegDeleteValue = clz.getDeclaredMethod("WindowsRegDeleteValue", //$NON-NLS-1$ new Class[] { int.class, byte[].class }); mWinRegDeleteValue.setAccessible(true); // open registry key Integer hSettings = (Integer) mOpenKey.invoke(userRoot, new Object[] { toByteArray(AUTOSTART_KEY), new Integer(KEY_ALL_ACCESS), new Integer(KEY_ALL_ACCESS) }); // check autostart settings if (autostart) { // find classpath entry for desktop client JAR: String path = JarUtilities.getJar(targetPatterns); // write autostart value mWinRegSetValue.invoke(userRoot, new Object[] { hSettings, toByteArray(AUTOSTART_ENTRY), toByteArray(path) }); } else { // delete autostart entry mWinRegDeleteValue.invoke(userRoot, new Object[] { hSettings, toByteArray(AUTOSTART_ENTRY) }); } // close registry key mCloseKey.invoke(Preferences.userRoot(), new Object[] { hSettings }); } catch (Exception e) { // TODO: throw exception and catch it outside to display an error dialog log.error("Error while writing registry entries.", e); //$NON-NLS-1$ } }
From source file:com.bjwg.back.util.ReflectionUtils.java
/** *//*from w w w . j av a2 s . c o m*/ public static Method getAccessibleMethod(final Object obj, final String methodName, final Class<?>... parameterTypes) { AssertUtils.notNull(obj, "object?"); for (Class<?> superClass = obj.getClass(); superClass != Object.class; superClass = superClass .getSuperclass()) { try { Method method = superClass.getDeclaredMethod(methodName, parameterTypes); method.setAccessible(true); return method; } catch (NoSuchMethodException e) {//NOSONAR } } return null; }