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();
}
I suspect your problem is one of the following:
filedoesn’t exist or hasn’t been properly specified. Check viafile.exists()Mainclass ispackage Test2;then your class file must be in the following location:C:\classes\Test2\Main.class.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.