Re: Dynamically loading classes at runtime
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.