Dynamically loading classes at runtime
1 posts in topic
Flat View  Flat View

Posted By:   Paul_Hunnisett
Posted On:   Saturday, April 27, 2002 05:07 AM

I'm trying to develop an application that will load classes that have been added to it's classpath at runtime. The names of these classes will not be known until runtime although I will know a type since they will all implement an interface so:

ClassA myClass = new ClassB

won't work since I don't know ClassB until runtime.

Re: Dynamically loading classes at runtime

Posted By:   Chris_Peyton  
Posted On:   Monday, May 6, 2002 07:02 PM

When creating a class through dynamic class loading, you need to cast it to the interface it implements. The interface is the part of the contract that you know how to operate on. So if you have interface A that has method foo() and class B implements inteface A, you would create dynamically like:

A a = (A)Class.forName("package.B").newInstance();

Basically, you are creating a new class dynamically of B's type, and then downcasting to the appropriate interface. If package.B is in the classpath, then this should be successfull, and then you can perform the operation as:


the real power is that you can make the dynamic type a property so it can be changed at runtime and be able to add classes on the fly.

Watch out for two exception, the ClassCastException and the ClassNotFoundException.
About | Sitemap | Contact