Example usage for java.net URLClassLoader URLClassLoader

List of usage examples for java.net URLClassLoader URLClassLoader

Introduction

In this page you can find the example usage for java.net URLClassLoader URLClassLoader.

Prototype

public URLClassLoader(URL[] urls) 

Source Link

Document

Constructs a new URLClassLoader for the specified URLs using the default delegation parent ClassLoader .

Usage

From source file:Main.java

public static void main(String[] argv) throws Exception {
    File file = new File("c:\\");

    URL url = file.toURI().toURL();
    URL[] urls = new URL[] { url };

    ClassLoader cl = new URLClassLoader(urls);

    Class cls = cl.loadClass("com.mycompany.MyClass");
}

From source file:Main.java

public static void main(String[] argv) throws Exception {
    File file = new File("c:\\class\\");
    URL url = file.toURI().toURL();
    URL[] urls = new URL[] { url };
    ClassLoader loader = new URLClassLoader(urls);
    Class cls = loader.loadClass("user.informatin.Class");
}

From source file:Main.java

static public void main(String args[]) throws Exception {
    URL myurl[] = { new URL("file:///C:/CH3/ClassLoader/web/"), new URL("http://www.java2s.edu/~xyx/test/") };
    URLClassLoader x = new URLClassLoader(myurl);
    Class c = x.loadClass("TestURL");

    Class getArg1[] = { (new String[1]).getClass() };
    Method m = c.getMethod("main", getArg1);
    String[] my1 = { "arg1 passed", "arg2 passed" };
    Object myarg1[] = { my1 };//from  w  w  w.j a v  a 2  s  .  c  o m
    m.invoke(null, myarg1);

    Object ob = c.newInstance();
    Class arg2[] = {};
    Method m2 = c.getMethod("tt", arg2);
    m2.invoke(ob, null);

    Class arg3[] = { (new String()).getClass(), int.class };
    Method m3 = c.getMethod("tt", arg3);
    Object myarg2[] = { "Arg1", new Integer(100) };
    m3.invoke(ob, myarg2);
}

From source file:Main.java

  public static void main(String[] argv) throws Exception {
  File file = new File("c:\\");

  URL url = file.toURI().toURL(); 
  URL[] urls = new URL[] { url };

  ClassLoader cl = new URLClassLoader(urls);

  Class cls = cl.loadClass("com.mycompany.MyClass");
}

From source file:MyClass.java

public static void main(String[] argv) throws Exception {

    URL[] urls = null;/* w  w  w  .  ja v  a 2s  . c  o  m*/

    File dir = new File(System.getProperty("user.dir") + File.separator + "dir" + File.separator);
    URL url = dir.toURI().toURL();
    urls = new URL[] { url };

    ClassLoader cl = new URLClassLoader(urls);

    Class cls = cl.loadClass("MyClass");

    MyClass myObj = (MyClass) cls.newInstance();

}

From source file:MinAppletviewer.java

public static void main(String args[]) throws Exception {
    AppSupport theAppSupport = new AppSupport();
    JFrame f = new JFrame();
    URL toload = new URL(args[0]);
    String host = toload.getHost();
    int port = toload.getPort();
    String protocol = toload.getProtocol();
    String path = toload.getFile();
    int join = path.lastIndexOf('/');
    String file = path.substring(join + 1);
    path = path.substring(0, join + 1);/* w  w  w  . j a  v  a  2s.  c om*/

    theAppSupport.setCodeBase(new URL(protocol, host, port, path));
    theAppSupport.setDocumentBase(theAppSupport.getCodeBase());

    URL[] bases = { theAppSupport.getCodeBase() };
    URLClassLoader loader = new URLClassLoader(bases);
    Class theAppletClass = loader.loadClass(file);
    Applet theApplet = (Applet) (theAppletClass.newInstance());

    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    f.add(theApplet, BorderLayout.CENTER);

    theApplet.setStub(theAppSupport);

    f.setSize(200, 200);
    f.setVisible(true);
    theApplet.init();
    theApplet.start();
}

From source file:com.mirth.connect.cli.launcher.CommandLineLauncher.java

public static void main(String[] args) {
    System.setProperty("log4j.configuration", "log4j-cli.properties");
    logger = Logger.getLogger(CommandLineLauncher.class);

    try {/*  w  ww  .j ava2 s  .co m*/
        ManifestFile mirthCliJar = new ManifestFile("cli-lib/mirth-cli.jar");
        ManifestFile mirthClientCoreJar = new ManifestFile("cli-lib/mirth-client-core.jar");
        ManifestDirectory cliLibDir = new ManifestDirectory("cli-lib");
        cliLibDir.setExcludes(new String[] { "mirth-client-core.jar" });

        ManifestEntry[] manifest = new ManifestEntry[] { mirthCliJar, mirthClientCoreJar, cliLibDir };

        List<URL> classpathUrls = new ArrayList<URL>();
        addManifestToClasspath(manifest, classpathUrls);
        addSharedLibsToClasspath(classpathUrls);
        URLClassLoader classLoader = new URLClassLoader(classpathUrls.toArray(new URL[classpathUrls.size()]));
        Class<?> cliClass = classLoader.loadClass("com.mirth.connect.cli.CommandLineInterface");
        Constructor<?>[] constructors = cliClass.getDeclaredConstructors();

        for (int i = 0; i < constructors.length; i++) {
            Class<?> parameters[] = constructors[i].getParameterTypes();

            if (parameters.length == 1) {
                constructors[i].newInstance(new Object[] { args });
                i = constructors.length;
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.kaazing.k3po.launcher.Launcher.java

/**
 * Main entry point to running K3PO.//from  ww  w .jav a 2 s  .c om
 * @param args to run with
 * @throws Exception if fails to run
 */
public static void main(String... args) throws Exception {
    Options options = createOptions();

    try {
        Parser parser = new PosixParser();
        CommandLine cmd = parser.parse(options, args);

        if (cmd.hasOption("version")) {
            System.out.println("Version: " + Launcher.class.getPackage().getImplementationVersion());
        }

        String scriptPathEntries = cmd.getOptionValue("scriptpath", "src/test/scripts");
        String[] scriptPathEntryArray = scriptPathEntries.split(";");
        List<URL> scriptUrls = new ArrayList<>();

        for (String scriptPathEntry : scriptPathEntryArray) {
            File scriptEntryFilePath = new File(scriptPathEntry);
            scriptUrls.add(scriptEntryFilePath.toURI().toURL());
        }

        String controlURI = cmd.getOptionValue("control");
        if (controlURI == null) {
            controlURI = "tcp://localhost:11642";
        }

        boolean verbose = cmd.hasOption("verbose");

        URLClassLoader scriptLoader = new URLClassLoader(scriptUrls.toArray(new URL[0]));
        RobotServer server = new RobotServer(URI.create(controlURI), verbose, scriptLoader);
        server.start();
        server.join();
    } catch (ParseException ex) {
        HelpFormatter helpFormatter = new HelpFormatter();
        helpFormatter.printHelp(Launcher.class.getSimpleName(), options, true);
    }

}

From source file:com.mirth.connect.server.launcher.MirthLauncher.java

public static void main(String[] args) {
    try {/*w  w w . jav  a2 s .c  o m*/
        try {
            uninstallPendingExtensions();
            installPendingExtensions();
        } catch (Exception e) {
            logger.error("Error uninstalling or installing pending extensions.", e);
        }

        Properties mirthProperties = new Properties();
        String includeCustomLib = null;

        try {
            mirthProperties.load(new FileInputStream(new File(MIRTH_PROPERTIES_FILE)));
            includeCustomLib = mirthProperties.getProperty(PROPERTY_INCLUDE_CUSTOM_LIB);
            createAppdataDir(mirthProperties);
        } catch (Exception e) {
            logger.error("Error creating the appdata directory.", e);
        }

        ManifestFile mirthServerJar = new ManifestFile("server-lib/mirth-server.jar");
        ManifestFile mirthClientCoreJar = new ManifestFile("server-lib/mirth-client-core.jar");
        ManifestDirectory serverLibDir = new ManifestDirectory("server-lib");
        serverLibDir.setExcludes(new String[] { "mirth-client-core.jar" });

        List<ManifestEntry> manifestList = new ArrayList<ManifestEntry>();
        manifestList.add(mirthServerJar);
        manifestList.add(mirthClientCoreJar);
        manifestList.add(serverLibDir);

        // We want to include custom-lib if the property isn't found, or if it equals "true"
        if (includeCustomLib == null || Boolean.valueOf(includeCustomLib)) {
            manifestList.add(new ManifestDirectory("custom-lib"));
        }

        ManifestEntry[] manifest = manifestList.toArray(new ManifestEntry[manifestList.size()]);

        // Get the current server version
        JarFile mirthClientCoreJarFile = new JarFile(mirthClientCoreJar.getName());
        Properties versionProperties = new Properties();
        versionProperties.load(mirthClientCoreJarFile
                .getInputStream(mirthClientCoreJarFile.getJarEntry("version.properties")));
        String currentVersion = versionProperties.getProperty("mirth.version");

        List<URL> classpathUrls = new ArrayList<URL>();
        addManifestToClasspath(manifest, classpathUrls);
        addExtensionsToClasspath(classpathUrls, currentVersion);
        URLClassLoader classLoader = new URLClassLoader(classpathUrls.toArray(new URL[classpathUrls.size()]));
        Class<?> mirthClass = classLoader.loadClass("com.mirth.connect.server.Mirth");
        Thread mirthThread = (Thread) mirthClass.newInstance();
        mirthThread.setContextClassLoader(classLoader);
        mirthThread.start();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.apache.commons.jci.examples.commandline.CommandlineCompiler.java

public static void main(String[] args) throws Exception {

    final Options options = new Options();

    options.addOption(OptionBuilder.withArgName("a.jar:b.jar").hasArg().withValueSeparator(':')
            .withDescription("Specify where to find user class files").create("classpath"));

    options.addOption(OptionBuilder.withArgName("release").hasArg()
            .withDescription("Provide source compatibility with specified release").create("source"));

    options.addOption(OptionBuilder.withArgName("release").hasArg()
            .withDescription("Generate class files for specific VM version").create("target"));

    options.addOption(OptionBuilder.withArgName("path").hasArg()
            .withDescription("Specify where to find input source files").create("sourcepath"));

    options.addOption(OptionBuilder.withArgName("directory").hasArg()
            .withDescription("Specify where to place generated class files").create("d"));

    options.addOption(OptionBuilder.withArgName("num").hasArg()
            .withDescription("Stop compilation after these number of errors").create("Xmaxerrs"));

    options.addOption(OptionBuilder.withArgName("num").hasArg()
            .withDescription("Stop compilation after these number of warning").create("Xmaxwarns"));

    options.addOption(OptionBuilder.withDescription("Generate no warnings").create("nowarn"));

    //        final HelpFormatter formatter = new HelpFormatter();
    //        formatter.printHelp("jci", options);

    final CommandLineParser parser = new GnuParser();
    final CommandLine cmd = parser.parse(options, args, true);

    ClassLoader classloader = CommandlineCompiler.class.getClassLoader();
    File sourcepath = new File(".");
    File targetpath = new File(".");
    int maxerrs = 10;
    int maxwarns = 10;
    final boolean nowarn = cmd.hasOption("nowarn");

    final JavaCompiler compiler = new JavaCompilerFactory().createCompiler("eclipse");
    final JavaCompilerSettings settings = compiler.createDefaultSettings();

    for (Iterator it = cmd.iterator(); it.hasNext();) {
        final Option option = (Option) it.next();
        if ("classpath".equals(option.getOpt())) {
            final String[] values = option.getValues();
            final URL[] urls = new URL[values.length];
            for (int i = 0; i < urls.length; i++) {
                urls[i] = new File(values[i]).toURL();
            }//from w ww .  j a va 2  s. c  om
            classloader = new URLClassLoader(urls);
        } else if ("source".equals(option.getOpt())) {
            settings.setSourceVersion(option.getValue());
        } else if ("target".equals(option.getOpt())) {
            settings.setTargetVersion(option.getValue());
        } else if ("sourcepath".equals(option.getOpt())) {
            sourcepath = new File(option.getValue());
        } else if ("d".equals(option.getOpt())) {
            targetpath = new File(option.getValue());
        } else if ("Xmaxerrs".equals(option.getOpt())) {
            maxerrs = Integer.parseInt(option.getValue());
        } else if ("Xmaxwarns".equals(option.getOpt())) {
            maxwarns = Integer.parseInt(option.getValue());
        }
    }

    final ResourceReader reader = new FileResourceReader(sourcepath);
    final ResourceStore store = new FileResourceStore(targetpath);

    final int maxErrors = maxerrs;
    final int maxWarnings = maxwarns;
    compiler.setCompilationProblemHandler(new CompilationProblemHandler() {
        int errors = 0;
        int warnings = 0;

        public boolean handle(final CompilationProblem pProblem) {

            if (pProblem.isError()) {
                System.err.println(pProblem);

                errors++;

                if (errors >= maxErrors) {
                    return false;
                }
            } else {
                if (!nowarn) {
                    System.err.println(pProblem);
                }

                warnings++;

                if (warnings >= maxWarnings) {
                    return false;
                }
            }

            return true;
        }
    });

    final String[] resource = cmd.getArgs();

    for (int i = 0; i < resource.length; i++) {
        System.out.println("compiling " + resource[i]);
    }

    final CompilationResult result = compiler.compile(resource, reader, store, classloader);

    System.out.println(result.getErrors().length + " errors");
    System.out.println(result.getWarnings().length + " warnings");

}