public AppletControl(String u, int w, int h, String user, String p) { PARAMETERS.put("RemoteHost", u.split("//")[1].split(":")[0]); PARAMETERS.put("RemotePort", u.split(":")[2].split("/")[0]); System.out.println(PARAMETERS.toString()); this.url = u; URL[] url = new URL[1]; try { url[0] = new URL(u); URLClassLoader load = new URLClassLoader(url); try { try { app = (Applet) load.loadClass("aplug").newInstance(); app.setSize(w, h); app.setStub(this); app.setVisible(true); } catch (InstantiationException ex) { ex.printStackTrace(); } catch (IllegalAccessException ex) { ex.printStackTrace(); } } catch (ClassNotFoundException ex) { ex.printStackTrace(); } } catch (MalformedURLException ex) { ex.printStackTrace(); } }
public HashMap<String, Class<?>> loadServiceJar() { List<JarConfig> list_confi = loadConfig(); HashMap<String, Class<?>> map = new HashMap<String, Class<?>>(); URL[] url = new URL[list_confi.size()]; for (int i = 0; i < url.length; ++i) { try { url[i] = new File(list_confi.get(i).getPath()).toURI().toURL(); } catch (MalformedURLException e) { e.printStackTrace(); } } ClassLoader parentClassLoader = Thread.currentThread().getContextClassLoader(); // First the load jar files delegate to application class loader, if not found // Using URL class loader as the second choice URLClassLoader classLoader = new URLClassLoader(url, parentClassLoader); for (int i = 0; i < list_confi.size(); ++i) { try { String Name = classLoader.loadClass(list_confi.get(i).getName()).getName(); Class<?> cl = classLoader.loadClass(list_confi.get(i).getClName()); map.put(Name, cl); } catch (Exception e) { e.printStackTrace(); } } return map; }
/** * Make a different ClassLoader that loads the same URLs as this one, and use it to compile an * {@code @AutoJson} class. If Velocity loads its managers using the context class loader, and * that loader is still the original one that loaded this test, then it will find the original * copy of the Velocity classes rather than the one from the new loader, and fail. * * <p>This test assumes that the test class was loaded by a URLClassLoader and that that loader's * URLs also include the Velocity classes. */ public void testClassLoaderHack() throws Exception { URLClassLoader myLoader = (URLClassLoader) getClass().getClassLoader(); URLClassLoader newLoader = new URLClassLoader(myLoader.getURLs(), myLoader.getParent()); String velocityClassName = Velocity.class.getName(); Class<?> myVelocity = myLoader.loadClass(velocityClassName); Class<?> newVelocity = newLoader.loadClass(velocityClassName); assertThat(myVelocity).isNotEqualTo(newVelocity); Runnable test = (Runnable) newLoader.loadClass(RunInClassLoader.class.getName()).newInstance(); assertThat(test.getClass()).isNotEqualTo(RunInClassLoader.class); test.run(); }
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)); } }
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); } }
@Override public Class<?> loadClass(String name, URI uri) { // platform:/resource/simple-jdbc-dao/src/main/resources/statements.meta String pname = getProjectName(uri); if (allLoaders == null) init(); boolean retry = false; if (pname != null) { URLClassLoader loader = allLoaders.get(pname); if (loader != null) { try { return loader.loadClass(name); } catch (ClassNotFoundException ignore) { } // for the case a new project is opened init(); loader = allLoaders.get(pname); if (loader != null) { try { return loader.loadClass(name); } catch (ClassNotFoundException ignore) { LOGGER.warn("Can't find class '" + name + "' in loader " + loader + " " + uri); } } else { retry = true; } } else { retry = true; } } if (!retry) return null; for (Entry<String, URLClassLoader> e : allLoaders.entrySet()) { try { Class<?> clazz = e.getValue().loadClass(name); LOGGER.warn("Found " + name + "(" + uri + ") in " + e.getKey()); return clazz; } catch (ClassNotFoundException ignore) { } } // for the case a new project is opened init(); for (Entry<String, URLClassLoader> e : allLoaders.entrySet()) { try { Class<?> clazz = e.getValue().loadClass(name); LOGGER.warn("Found " + name + "(" + uri + ") in " + e.getKey()); return clazz; } catch (ClassNotFoundException ignore) { } } LOGGER.warn("Can't find class '" + name + "' in any loader " + allLoaders); return null; }
/* *加载class,直接调用 myClassLoader的loadClass(className)方法 */ public Class<?> loadClass(String className) throws ModuleNotFoundException { try { return urlClassLoader.loadClass(className); } catch (ClassNotFoundException e) { throw new ModuleNotFoundException(className); } }
public NationClassLoader(URL[] urls, Vector nations) { super(urls); for (int i = 0; i < urls.length; i++) { file = urls[i].getFile(); fileTmp = new File(file); System.out.println( "NationClassLoader - Does " + fileTmp.toString() + " exists : " + fileTmp.exists()); name = file.substring(file.lastIndexOf("/") + 1, file.lastIndexOf(".")); runtimeObject = null; try { jarLoader = URLClassLoader.newInstance(new URL[] {urls[i]}); System.out.println( "NationClassLoader - JARloader trying : " + jarLoader.getURLs()[0].toString()); runtimeObject = jarLoader.loadClass(name + "/" + name).newInstance(); } catch (Exception e) { System.err.println("NationClassLoader - Stinking error : " + e); } if (runtimeObject != null) { natFile = (nationFile2) runtimeObject; nations.addElement(natFile); } } }
public void invoke(Request request, Response response) throws IOException, ServletException { String servletName = ((HttpServletRequest) request).getRequestURI(); servletName = servletName.substring(servletName.lastIndexOf("/") + 1); URLClassLoader loader = null; try { URL[] urls = new URL[1]; URLStreamHandler streamHandler = null; File classPath = new File(WEB_ROOT); String repository = (new URL("file", null, classPath.getCanonicalPath() + File.separator)).toString(); urls[0] = new URL(null, repository, streamHandler); loader = new URLClassLoader(urls); } catch (IOException e) { System.out.println(e.toString()); } Class myClass = null; try { myClass = loader.loadClass(servletName); } catch (ClassNotFoundException e) { System.out.println(e.toString()); } Servlet servlet = null; try { servlet = (Servlet) myClass.newInstance(); servlet.service((HttpServletRequest) request, (HttpServletResponse) response); } catch (Exception e) { System.out.println(e.toString()); } catch (Throwable e) { System.out.println(e.toString()); } }
public Object getPlugin(String protocol) throws InstantiationException, IllegalAccessException { String className = this.map.get(protocol); List<URL> urlList = new ArrayList<URL>(); Class c1 = null; try { // load all class of plugin URL classesUrl = new URL("file:" + this.pluginDirPath + "/WEB-INF/classes/"); urlList.add(classesUrl); // load lib of plugin File libDir = new File(this.pluginDirPath + "/WEB-INF/lib"); for (File lib : libDir.listFiles()) { URL url = new URL("file:" + lib.getAbsolutePath()); urlList.add(url); } URL[] urlArray = (URL[]) urlList.toArray(new URL[0]); URLClassLoader urlClassLoader1 = new URLClassLoader(urlArray, this.getClass().getClassLoader()); c1 = urlClassLoader1.loadClass(className); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } return c1.newInstance(); }
@SuppressWarnings({"rawtypes", "unchecked", "resource"}) @Override public Object createExecutableExtension(String propertyName) throws CoreException { try { String className = attributes.get(propertyName); IProject project = getProject(); IJavaProject javaProject = JavaCore.create(project); String[] classPathEntries = JavaRuntime.computeDefaultRuntimeClassPath(javaProject); List<URL> urlList = new ArrayList<URL>(); for (int i = 0; i < classPathEntries.length; i++) { String entry = classPathEntries[i]; IPath path = new Path(entry); URL url = path.toFile().toURI().toURL(); urlList.add(url); } ClassLoader parentClassLoader = javaProject.getClass().getClassLoader(); URL[] urls = (URL[]) urlList.toArray(new URL[urlList.size()]); URLClassLoader classLoader = new URLClassLoader(urls, parentClassLoader); ClassLoader cl = classLoader.getParent(); Class clazz = classLoader.loadClass(className); return clazz.getConstructor().newInstance(); } catch (Exception ex) { ex.printStackTrace(); throw new CoreException(new Status(IStatus.ERROR, Activator.PLUGIN_ID, ex.getMessage())); } }
public static void main(String[] args) { if (System.getProperty("profile") != null) { System.out.println("Starting"); System.setProperty("profile", String.valueOf(System.nanoTime())); } try { URL[] urls = getJarUrls(); ClassLoader parentLoader = Thread.currentThread().getContextClassLoader(); URLClassLoader loader; if (parentLoader != null) loader = new URLClassLoader(urls, parentLoader); else loader = new URLClassLoader(urls); Class beesClass = loader.loadClass(BEES_CLASS); Thread.currentThread().setContextClassLoader(loader); Method mainMethod = beesClass.getDeclaredMethod("main", String[].class); Object obj = mainMethod.invoke(null, new Object[] {args}); int returnValue = 0; if (obj instanceof Integer) { returnValue = ((Integer) obj).intValue(); } System.exit(returnValue); } catch (Throwable e) { e.printStackTrace(); } }
@SuppressWarnings("unchecked") private static void loadBots() { logger.info("Loading available bots"); final Collection<File> botJars = FileUtils.listFiles(botsDirecotry, new String[] {"jar"}, false); for (File botJar : botJars) { try { JarFile jar = new JarFile(botJar); ZipEntry entry = jar.getEntry("bot.yml"); if (entry == null) throw new RuntimeException("Bot has no bot.yml file!"); InputStream is = jar.getInputStream(entry); YAMLNode n = new YAMLNode(new Yaml().loadAs(is, Map.class), true); String mainClass = n.getString("mainClass"); String type = n.getString("type"); URLClassLoader loader = new URLClassLoader(new URL[] {botJar.toURI().toURL()}, Chatty.class.getClassLoader()); BOT_INFO.put(type, new BotClassInfo(loader.loadClass(mainClass).asSubclass(Bot.class), n)); logger.info("Loaded bot '{}'", type); } catch (Exception e) { logger.error("Failed to load bot from {}", botJar.getName()); e.printStackTrace(); } } logger.info("Loaded {} bot(s)", BOT_INFO.size()); }
private static void loadJar(String jar) { System.out.println("start load from " + jar); try { URL url = new URL(jar); URLClassLoader loader = new URLClassLoader(new URL[] {url}); Class<?> c = loader.loadClass("ny.test.TestPrint"); // c.getm Object o = c.newInstance(); ((TestJni) o).testJniPrint("test"); loader.close(); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InstantiationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
@SuppressWarnings("resource") private InitStep loadInitStep(Path jar) { try { URLClassLoader pluginLoader = new URLClassLoader( new URL[] {jar.toUri().toURL()}, InitPluginStepsLoader.class.getClassLoader()); try (JarFile jarFile = new JarFile(jar.toFile())) { Attributes jarFileAttributes = jarFile.getManifest().getMainAttributes(); String initClassName = jarFileAttributes.getValue("Gerrit-InitStep"); if (initClassName == null) { return null; } @SuppressWarnings("unchecked") Class<? extends InitStep> initStepClass = (Class<? extends InitStep>) pluginLoader.loadClass(initClassName); return getPluginInjector(jar).getInstance(initStepClass); } catch (ClassCastException e) { ui.message( "WARN: InitStep from plugin %s does not implement %s (Exception: %s)\n", jar.getFileName(), InitStep.class.getName(), e.getMessage()); return null; } catch (NoClassDefFoundError e) { ui.message( "WARN: Failed to run InitStep from plugin %s (Missing class: %s)\n", jar.getFileName(), e.getMessage()); return null; } } catch (Exception e) { ui.message( "WARN: Cannot load and get plugin init step for %s (Exception: %s)\n", jar, e.getMessage()); return null; } }
@SuppressWarnings("unchecked") private static void startPlugins() { logger.info("Loading available plugins"); final Collection<File> botJars = FileUtils.listFiles(pluginsDirecotry, new String[] {"jar"}, false); for (File botJar : botJars) { try { JarFile jar = new JarFile(botJar); ZipEntry ze = jar.getEntry("plugin.yml"); if (ze == null) throw new RuntimeException("Plugin has no plugin.yml file!"); InputStream is = jar.getInputStream(ze); YAMLNode n = new YAMLNode(new Yaml().loadAs(is, Map.class), true); String mainClass = n.getString("mainClass"); String name = n.getString("name"); URLClassLoader loader = new URLClassLoader(new URL[] {botJar.toURI().toURL()}, Chatty.class.getClassLoader()); Plugin plugin = loader.loadClass(mainClass).asSubclass(Plugin.class).newInstance(); plugin.start(); PLUGIN_INFO.put(name, new PluginInfo(name, plugin, n)); logger.info("Loaded plugin '{}'", name); } catch (Exception e) { logger.error("Failed to load plugin from {}", botJar.getName()); e.printStackTrace(); } } logger.info("Loaded {} plugin(s)", PLUGIN_INFO.size()); }
/** * Instantiates a new Standalone * * @param classLoader the ClassLoader used to instantiate class * @param args the arguments passed to Standalone * @throws ClassNotFoundException * @throws InstantiationException * @throws IllegalAccessException * @throws InvocationTargetException */ private void newStandalone(URLClassLoader classLoader, String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, InvocationTargetException { Class nanoStandalone = classLoader.loadClass("org.nanocontainer.Standalone"); Constructor constructor = nanoStandalone.getConstructors()[0]; constructor.newInstance(args); }
@SuppressWarnings("deprecation") public static void main(String[] args) { try { File fl = new File("testfile"); int idx = fl.getAbsolutePath().lastIndexOf("testfile"); String path = fl.getAbsolutePath().substring(0, idx); String phoenixHome = path + "src/test/resources/james-server/"; ArrayList<URL> classLoaderURLList = new ArrayList<URL>(); System.setProperty("phoenix.home", phoenixHome); classLoaderURLList.add(new File(phoenixHome + "bin/phoenix-loader.jar").toURL()); URL classLoaderURLArray[] = classLoaderURLList.toArray(new URL[classLoaderURLList.size()]); // System.setProperty( "catalina.home", "C:\\Program Files\\Apache Software Foundation\\Tomcat // 5.5"); URLClassLoader childClassLoader = new URLClassLoader(classLoaderURLArray, JamesLoader.class.getClassLoader()); final Class<?> mainClass = childClassLoader.loadClass("org.apache.avalon.phoenix.launcher.Main"); final Class<?>[] paramTypes = new Class[] {args.getClass()}; final Method method = mainClass.getMethod("main", paramTypes); Object main_instance = mainClass.newInstance(); method.invoke(main_instance, new Object[] {args}); } catch (Exception e) { e.printStackTrace(); } }
public static void main(String[] args) throws Exception { String rt = "\r\n"; String src = "package com.bjsxt.proxy;" + rt + "public class TankTimeProxy implements Moveable {" + rt + " public TankTimeProxy(Moveable t) {" + rt + " super();" + rt + " this.t = t;" + rt + " }" + rt + " Moveable t;" + rt + " @Override" + rt + " public void move() {" + rt + " long start = System.currentTimeMillis();" + rt + " System.out.println(\"starttime:\" + start);" + rt + " t.move();" + rt + " long end = System.currentTimeMillis();" + rt + " System.out.println(\"time:\" + (end-start));" + rt + " }" + rt + "}"; String fileName = System.getProperty("user.dir") + "/src/com/bjsxt/proxy/TankTimeProxy.java"; File f = new File(fileName); FileWriter fw = new FileWriter(f); fw.write(src); fw.flush(); fw.close(); // compile JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); StandardJavaFileManager fileMgr = compiler.getStandardFileManager(null, null, null); Iterable units = fileMgr.getJavaFileObjects(fileName); CompilationTask t = compiler.getTask(null, fileMgr, null, null, null, units); t.call(); fileMgr.close(); // load into memory and create an instance URL[] urls = new URL[] {new URL("file:/" + System.getProperty("user.dir") + "/src")}; URLClassLoader ul = new URLClassLoader(urls); Class c = ul.loadClass("com.bjsxt.proxy.TankTimeProxy"); System.out.println(c); Constructor ctr = c.getConstructor(Moveable.class); Moveable m = (Moveable) ctr.newInstance(new Tank()); m.move(); }
@Override public Class<?> loadFromScriptClassLoader(String path) throws ClassNotFoundException { if (scriptClassLoader == null) { return loadFromRuntimeLibraryLoader(path); } Class<?> scriptClass = scriptClassLoader.loadClass(path); return scriptClass; }
public void process(Request request, Response response) { String uri = request.getUri(); String servletName = uri.substring(uri.lastIndexOf("/") + 1); URLClassLoader loader = null; try { // create a URLClassLoader URL[] urls = new URL[1]; URLStreamHandler streamHandler = null; File classPath = new File(Constants.WEB_ROOT); // the forming of repository is taken from the createClassLoader method in // org.apache.catalina.startup.ClassLoaderFactory String repository = (new URL("file", null, classPath.getCanonicalPath() + File.separator)).toString(); // the code for forming the URL is taken from the addRepository method in // org.apache.catalina.loader.StandardClassLoader class. urls[0] = new URL(null, repository, streamHandler); loader = new URLClassLoader(urls); } catch (IOException e) { System.out.println(e.toString()); } Class myClass = null; try { myClass = loader.loadClass(servletName); } catch (ClassNotFoundException e) { System.out.println(e.toString()); } Servlet servlet = null; try { servlet = (Servlet) myClass.newInstance(); servlet.service((ServletRequest) request, (ServletResponse) response); } catch (Exception e) { System.out.println(e.toString()); } catch (Throwable e) { System.out.println(e.toString()); } // this is to run application1 by another way /* * URL myUrl[]={new URL("file:///D:/github/Toy-Tomcat/Tomcat/TOMCAT/src/")}; URLClassLoader x = new URLClassLoader(myUrl); Class myClass = x.loadClass("test.PrimitiveServlet"); Servlet servlet = null; try { servlet = (Servlet) myClass.newInstance(); servlet.service((ServletRequest) request, (ServletResponse) response); } catch (Exception e) { System.out.println(e.toString()); } catch (Throwable e) { System.out.println(e.toString()); } */ }
public static DatabaseBridge loadBridge(File file) { DatabaseBridge theBridge = null; PluginDescriptionFile bridgeDescription = null; try { // Load the jar JarFile jar = new JarFile(file); // Load the info about the bridge JarEntry entry = jar.getJarEntry("bridge.yml"); InputStream stream = jar.getInputStream(entry); bridgeDescription = new PluginDescriptionFile(stream); // Get the main class String main = bridgeDescription.getMain(); try { URL test = new URL( "http://guardian.nekotech.tk:8080/job/Guardian-MySQL/Guardian-MySQL-RB/api/json"); HttpURLConnection connection = (HttpURLConnection) test.openConnection(); connection.connect(); JSONObject object = (JSONObject) new JSONParser().parse(new InputStreamReader(connection.getInputStream())); String version = bridgeDescription.getVersion(); if (!version.equals("Unknown") && Integer.parseInt(version) < Integer.parseInt(object.get("number").toString())) { BukkitUtils.info("Guardian-Bridge is out of date, please download the latest"); } } catch (Exception ex) { BukkitUtils.severe("Error occurred while checking if Guardian is up to date", ex); } // Clean it all up stream.close(); jar.close(); // Get a new classloader URLClassLoader classLoader = new URLClassLoader( new URL[] {file.toURI().toURL()}, DatabaseBridge.class.getClassLoader()); // Load the class Class<?> clazz = classLoader.loadClass(main); // Construct it Object object = clazz.newInstance(); // Verify it if (!(object instanceof DatabaseBridge)) { return null; } // Its all good theBridge = (DatabaseBridge) object; } catch (FileNotFoundException ex) { BukkitUtils.severe("Database bridge does not contain a valid bridge.yml"); } catch (ZipException ex) { BukkitUtils.severe("The database bridge appears to be an invalid jar file"); } catch (Exception ex) { ex.printStackTrace(); } Guardian.getInstance().getConf().bridgeDescription = bridgeDescription; BukkitUtils.info( "Loading " + bridgeDescription.getName() + " v" + bridgeDescription.getVersion()); // Lets return it return theBridge; }
static void extractJpaClasses( final URLClassLoader classLoader, final List<String> classes, final JpaDependencyDiagramModel dependencyModel, final String includePatternString, final String excludePatternString) throws ClassNotFoundException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException { String[] includePatterns = includePatternString.split(","); String[] excludePatterns = excludePatternString.split(","); boolean hasAnyPatterns = !(includePatterns.length == 1 && includePatterns[0].isEmpty()) || !(excludePatterns.length == 1 && excludePatterns[0].isEmpty()); Map<String, Map<String, JpaDependencyType>> jpaDependencyCache = new HashMap<String, Map<String, JpaDependencyType>>(); for (String className : classes) { if (UmlGeneratorUtility.isIncluded( className, hasAnyPatterns, includePatterns, excludePatterns)) { Class<?> loadClass = classLoader.loadClass(className); // check if its an persistent entity if (isPersistentEntity(loadClass)) { System.out.println("Parsing persistent class " + loadClass.getSimpleName()); // extract class info JpaClassModel classModel = new JpaClassModel(loadClass.getName()); // determine class types extractJpaClassAnnotations(loadClass, classModel); // extract fields extractColumnsAndEntityDependencies( dependencyModel, loadClass, classModel, jpaDependencyCache, hasAnyPatterns, includePatterns, excludePatterns); // extract interfaces extractInterfaces( loadClass, classModel, hasAnyPatterns, includePatterns, excludePatterns); // extract parent class Class<?> superclass = loadClass.getSuperclass(); if (superclass != null && !superclass.equals(Object.class) && UmlGeneratorUtility.isIncluded( superclass.getName(), hasAnyPatterns, includePatterns, excludePatterns)) { classModel.setParent(superclass.getName()); } // add prepared class model to class diagram dependencyModel.addClass(classModel); } } } }
public static Class<?> getProviderClass( String fullPathOfProviderPackage, String providerClassName) throws Exception { URLClassLoader urlcl = URLClassLoader.newInstance( new URL[] {new URL("file:////F:/connector/jmsprovider/activemq-all-5.9.1.jar")}); Class<?> clazz = urlcl.loadClass(providerClassName); return clazz; }
/** * Consider this example. * * <p>Your application code contains a helper method that calls * * <pre> * Class.forName(classNameString). * * That method is called from a plugin class. * * The classNameString specifies a class that is contained in the plugin * JAR. * </pre> * * <p>The author of the plugin has the reasonable expectation that the class should be loaded. * However, the helper method's class was loaded by the system class loader, and that is the class * loader used by Class.forName. The classes in the plugin JAR are not visible. This phenomenon is * called classloader inversion. * * <p>To overcome this problem, the helper method needs to use the correct class loader. It can * require the class loader as a parameter. Alternatively, it can require that the correct class * loader is set as the context class loader of the current thread. * * <p>Each thread has a reference to a class loader, called the context class loader. The main * thread's context class loader is the system class loader. When a new thread is created, its * context class loader is set to the creating thread's context class loader. Thus, if you don't * do anything, then all threads have their context class loader set to the system class loader. * * <p>The helper method can then retrieve the context class loader: * * <pre> * Thread t = Thread.currentThread(); * ClassLoader loader = t.getContextClassLoader(); * Class cl = loader.loadClass(className); * </pre> * * <p>It might surprise you, however, that you can have two classes in the same virtual machine * that have the same class and package name. A class is determined by its full name and the class * loader. This technique is useful for loading code from multiple sources. For example, a browser * uses separate instances of the applet class loader class for each web page. This allows the * virtual machine to separate classes from different web pages, no matter what they are named. * * <p>Because each applet is loaded by a separate class loader, these classes are entirely * distinct and do not conflict with each other. */ public void testLoadPluginClasses() { try { URL url = new URL("file:///path/to/plugin.jar"); URLClassLoader pluginLoader = new URLClassLoader(new URL[] {url}); Class<?> cl = pluginLoader.loadClass("mypackage.MyClass"); } catch (Exception e) { } }
@Test public void test2() throws Exception { URL jar = new URL("file:txazo-reflection-remote-service.jar"); URLClassLoader urlClassLoader = new URLClassLoader(new URL[] {jar}, Thread.currentThread().getContextClassLoader()); Class<?> versionApiClass = urlClassLoader.loadClass("org.txazo.reflection.remote.service.VersionService"); Class<?> versionApiClass1 = urlClassLoader.loadClass("org.txazo.reflection.remote.service.VersionService"); URLClassLoader urlClassLoader2 = new URLClassLoader(new URL[] {jar}, Thread.currentThread().getContextClassLoader()); Class<?> versionApiClass2 = urlClassLoader2.loadClass("org.txazo.reflection.remote.service.VersionService"); Assert.assertSame(versionApiClass, versionApiClass1); Assert.assertSame(versionApiClass, versionApiClass2); }
private static void executeForeignMethod(int port, URLClassLoader loader) throws SecurityException, InvocationTargetException, ClassNotFoundException, NoSuchMethodException, IllegalAccessException, MalformedURLException, IllegalArgumentException { String className = "SimpletestSigned1"; Class<?> cls = loader.loadClass(className); Method m = cls.getMethod("main", new Class[] {new String[0].getClass()}); System.out.println("executing " + className + "'s main"); m.invoke(null, (Object) new String[0]); }
public BootstrapSrcDBEventReader( DataSource dataSource, BootstrapEventBuffer eventBuffer, StaticConfig config, List<OracleTriggerMonitoredSourceInfo> sources, Map<String, Long> lastRows, Map<String, String> lastKeys, long sinceSCN) throws Exception { super("BootstrapSrcDBEventReader"); List<OracleTriggerMonitoredSourceInfo> sourcesTemp = new ArrayList<OracleTriggerMonitoredSourceInfo>(); sourcesTemp.addAll(sources); _sources = Collections.unmodifiableList(sourcesTemp); _dataSource = dataSource; _bootstrapSeedWriter = eventBuffer; _keyTxnFilesMap = new HashMap<String, File>(); _numRowsPerQuery = config.getNumRowsPerQuery(); _keyTxnBufferSizeMap = config.getKeyTxnBufferSizeMap(); Map<String, String> keyTxnFiles = config.getKeyTxnFilesMap(); Iterator<Entry<String, String>> itr = keyTxnFiles.entrySet().iterator(); while (itr.hasNext()) { Entry<String, String> entry = itr.next(); LOG.info("Adding KeyTxnMapFile Entry :" + entry); _keyTxnFilesMap.put(entry.getKey(), new File(entry.getValue())); } _enableNumRowsQuery = config.isEnableNumRowsQuery(); _commitInterval = config.getCommitInterval(); _numRowsPrefetch = config.getNumRowsPrefetch(); _LOBPrefetchSize = config.getLOBPrefetchSize(); _numRetries = config.getNumRetries(); _sinceSCN = sinceSCN; _lastRows = new HashMap<String, Long>(lastRows); _lastKeys = new HashMap<String, String>(lastKeys); _pKeyNameMap = config.getPKeyNameMap(); _pKeyTypeMap = config.getPKeyTypeMap(); _pKeyIndexMap = config.getPKeyIndexMap(); _queryHintMap = config.getQueryHintMap(); _eventQueryMap = config.getEventQueryMap(); _beginSrcKeyMap = config.getBeginSrcKeyMap(); _endSrcKeyMap = config.getEndSrcKeyMap(); File file = new File("ojdbc6-11.2.0.2.0.jar"); URL ojdbcJarFile = file.toURL(); URLClassLoader cl = URLClassLoader.newInstance(new URL[] {ojdbcJarFile}); _oraclePreparedStatementClass = cl.loadClass("oracle.jdbc.OraclePreparedStatement"); _setLobPrefetchSizeMethod = _oraclePreparedStatementClass.getMethod("setLobPrefetchSize", int.class); validate(); }
@Test public void test1() throws Exception { URL jar = new URL("file:txazo-reflection-remote-service.jar"); URLClassLoader urlClassLoader = new URLClassLoader(new URL[] {jar}, Thread.currentThread().getContextClassLoader()); Class<VersionApi> versionApiClass = (Class<VersionApi>) urlClassLoader.loadClass("org.txazo.reflection.remote.service.VersionService"); VersionApi versionApi = versionApiClass.newInstance(); Assert.assertEquals("1.0", versionApi.getVersion()); }
public static void loadLocal(final List<ScriptInfo> scripts, final File directory) throws ClassNotFoundException, InstantiationException, IllegalAccessException, FileNotFoundException, IOException { final List<File> classes = new ArrayList<File>(); for (final File file : directory.listFiles()) { if (file.isDirectory()) { putClasses(classes, file); } else if (file.toString().endsWith(".class")) { classes.add(file); } } for (final File file : classes) { final ClassGen cg = new ClassGen(new ClassParser(file.toURI().toURL().openStream(), file.getName()).parse()); final String className = cg.getClassName(); String fileDir; if (className.indexOf('.') != -1) { final String classDir = className.substring(0, className.indexOf('.')); fileDir = getDirectory(file).toString(); fileDir = fileDir.substring(0, fileDir.indexOf(classDir + '/')); } else { fileDir = directory.toURI().toURL().toString(); } final URLClassLoader loader = new URLClassLoader(new URL[] {new URL(fileDir)}) { public Class loadClass(String name, final boolean resolve) throws ClassNotFoundException { name = name.replace('/', '.').replace('\\', '.'); return super.loadClass(name, resolve); } }; Class<?> clazz; try { clazz = loader.loadClass(className); } catch (Exception e) { e.printStackTrace(); clazz = null; } if (clazz != null) { if (clazz.isAnnotationPresent(ScriptManifest.class)) { final ScriptManifest manifest = clazz.getAnnotation(ScriptManifest.class); scripts.add( new ScriptInfo( manifest.name(), manifest.description(), clazz, manifest.authors(), manifest.version(), manifest.type())); } } loader.close(); } }