Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

create an instance of a loaded class

Status
Not open for further replies.

davikokar

Technical User
May 13, 2004
523
IT
hallo,

I have an abstract class and some classes that extends it.
I would like to be able to load an external class (that extends my abstract class) and use it in my program.

I defined a classLoader to look for and define the external class (saved in the filesystem as a .class file).

This procedure works fine, but then I have problems in creating an instance of the class.

code so far:
Code:
import java.lang.reflect.*;
import java.lang.Exception.*;

public class MainClass 
{
    public static void main(String[] args)
    {      
        myLoader loader = new myLoader();
        try
        {
            Class newClass = loader.findClass("c:\\test\\test");
            
\\ to check if the class was loaded I print its methods (it works)            
Method m[] = newClass.getDeclaredMethods();
            for (int i = 0; i < m.length; i++)
            {
                System.out.println(m[i].toString());
            }          
            // here I should instantate the class...

        }      
        catch (ClassNotFoundException ex)
        {
            System.out.println(ex.toString());
        }
    }
}


any ideas, examples? I guess I should use newInstance() method. But how? Thanks
 
I wrote the class myself for testing reasons. In the real case I won't have written the class myself.

How do I use its constructor?
 
Does the ctor take any arguments?

I don't use reflection on a daily basis, but this worked for me:
Code:
 String cn = "pled.plugins." + s.substring (0, l - 6);
Class c;
try
{
	c = Class.forName (cn);
}
catch (UnsatisfiedLinkError ule)
{
	System.err.println ("Error loading plugin: " + cn);
	ule.printStackTrace();
	continue;
}
try
{
	Object o = c.newInstance ();
	PledPlugin pc = (PledPlugin) o;
Loading with Class.forName (String) and casting the result of newInstance to my interface.

don't visit my homepage:
 
This is a snippit form a program that dynamically creates an instance of a class... Hope this helps

Code:
// instantiate the function processor class if it exists
            Class c = Class.forName("parser.functionProcessors." + funcName);
            FunctionProcessorInterface fp = (FunctionProcessorInterface)c.newInstance();
            fp.someMethod();
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top