Hello all,

very useful forum you guys have here. maybe you might be able to help me with an issue i am having with a program i am writing? I am trying to dynamically load a class that the user specifies. I am coding in standard java 1.5 and swing. what i have found so far is as follows...

Code:

Class c = Class.forName( "com.mindprod.mypackage.Myclass" ); Thing t = (Thing)c.newInstance( ); t.doSomething();


The forName() method takes a String that is the *NAME* of the class, my program uses a JFileChooser and the method getSelectedFile that returns a (.class) File that needs to be dynamicaly loaded. I need a way to do this, some thought would be...

* Get the path of the returned file and somehow turn it into a class name.
* Some other way of loading a class based upon the file path not name.

If anyone has any ideas i will be very grateful,

Thanks heaps,

Andrew.
Edit/Delete Message

Recommended Answers

All 2 Replies

* Get the path of the returned file and somehow turn it into a class name.

I think that is your best option, but there are a couple of considerations to keep in mind.
1) you can reliably know the base path to the classes they have to choose from and the package structure is intact from that base.
2) you know or can determine the type of object being created so you can properly cast the Object from newInstance().

Given those two caveats, this tiny example illustrates using the selected file to load the class. I used two different variations for the baseDir, one which was on my classpath at the time of execution and one which was not. Both worked fine.

JFileChooser chooser = new JFileChooser();
int result = chooser.showOpenDialog(null);
if (result==JFileChooser.APPROVE_OPTION){
    File f = chooser.getSelectedFile();
    //String baseDir = System.getProperty("user.dir")+"\\build\\classes\\";
    String baseDir = "C:\\TEMP\\build\\classes\\";
    String className = f.getPath().replace(baseDir,"").replace(".class","").replace("\\",".");
    try {
        Class c = Class.forName(className);
        c.newInstance().toString();
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

Thanks, that looks like it might be useful.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.