Dynamic class loading
Why do we need to use dynamic class loading? Classes are loaded when we use them at first time, so if we don't use the class, it will never be loaded. Even if we use dynamic class loading:
A a = (A)Class.forName("A").newInstance();
we still have to know about A class at compile time. If we need to use class A we can simply create it using constructor(and it will be loaded into memory):
A a = new A();
If we don't need any instance of 开发者_如何学GoA class the code that contains an invocation of constructor of A class will never be executed, so it will never be loaded to the memory
You do not need to know about the class at compile-time.
You can read a class name from a configuration file, then cast it to an interface, without hardcoding any classnames at all.
Consider
SomeInterface a = (SomeInterface)Class.forName(config.readSomething()).newInstance();
we still have to know about A class at compile time.
ahem...
public interface Foo {..}
in a separate jar,
public class Bar implements Foo{..}
then
Foo f = (Foo)Class.forName("Bar").newInstance();
精彩评论