Paulywog
Paulywog

Reputation: 244

Why isn't my class being loaded through the external class loader?

I want to run the constructor of the Main.class in the package Test2, located in the folder C:\classes\

This is the code I'm using. It throws a class not found exception when it tries to turn it into a class. And then once it's part of the class object, will the constructor automatically be run, or do I have to instance it somehow? Test2 is inputted into this code as text.

    if (Main.os.equals("Windows"))
    {
        String path = "C:\\classes\\";
    }
    else
    {
        String path = "~/classes/";
    }

    File file = new File(path);

    try
    {
        URL url = file.toURI().toURL();
        URL[] urls = new URL[]{url};
        Main.print("Stage 1");
        ClassLoader cl = new URLClassLoader(urls);
        Main.print("Stage 2");
        Class cls = cl.loadClass(text + ".Main");
        Main.print(text + " was loaded into memory.");
        close();
    }
    catch (MalformedURLException e)
    {
        e.printStackTrace();
    }
    catch (ClassNotFoundException e)
    {
        e.printStackTrace();
    }

Upvotes: 0

Views: 424

Answers (2)

Muel
Muel

Reputation: 4425

I suspect your problem is one of the following:

  1. file doesn't exist or hasn't been properly specified. Check via file.exists()
  2. Your class file is not located in the correct directory. If the package declaration for the Main class is package Test2; then your class file must be in the following location: C:\classes\Test2\Main.class.
  3. If Main is nested class, then you will need to refer to the enclosing class when loading it, eg cl.loadClass("Test2.EnclosingClass$Main");

My guess it that your problem is number 2! :)

Good luck.

Oh, and yes, you'll need to create an instance of your object if you want the constructor to be called: clazz.newInstance() is the simplest method for no-args constructors.

Upvotes: 1

Bruce Martin
Bruce Martin

Reputation: 10543

Can you post the exact error message.

But here is how I execute a main method of using a class loader

    urlLoader = new URLClassLoader(urls);

    Class runClass = urlLoader.loadClass(classToRun);
    System.out.println("Starting Program !!!");

    Object[] arguments = new Object[]{args};
    Method mainMethod = runClass.getMethod("main", new Class[] {args.getClass()});
    mainMethod.invoke(null, arguments);

Note: classToRun will be the full package/class definition i.e. net.sf.RecordEditor.edit.FullEditor

Note: I use it to load from jar files, it will be similar for directories

It is taken from the run class here

http://record-editor.svn.sourceforge.net/viewvc/record-editor/Source/RecordEditor/src/net/sf/RecordEditor/utils/Run.java?revision=65&view=markup

An example of calling the class is here http://record-editor.svn.sourceforge.net/viewvc/record-editor/Source/RecordEditor/src/net/sf/RecordEditor/RunFullEditor.java?revision=65&view=markup

Upvotes: 0

Related Questions