java - Difference in functionality between instance created by classloader and new keyword -


i little bit confused in class loading , initializing concept

1: class.forname("test.employee").newinstance(); 2: classloader.getsystemclassloader().loadclass("test.employee").newinstance(); 3: new test.employee();  

every line of above written code creating instance of employee class don't understand difference in 3 methods.

the core differences between 3 approaches come down how classes located @ runtime , can them.

for example...

class.forname("test.employee").newinstance(); 

will use current class's classloader search class named employee in test package. allow discover classes might not available @ compile time , loaded dynamically same class loader context. search it's parent class loaders if class not found within current context...

classloader.getsystemclassloader().loadclass("test.employee").newinstance(); 

this use "system" classloader, typically 1 launched main application.

using either of these 2 methods great way generate dynamic applications actual implementation of class not known @ compile type. problem here can affect visibility , restrict can loaded classes.

for example, while may have loaded test.employee class , created instance of it, unless have reference test.employee @ compile time, want able cast it. typically interfaces come in handy.

equally, create own classloader instance , load classes or jars @ runtime provide, example, plugins, factories or managers implementation unknown @ compile time. functionality these would, typically, described through use of interfaces.

examples include java.awt.toolkit , jdbc java.sql.driver

at end of day, classloader mechanism providing means class file can loaded , instantiated current jvm. new keyword similar job, results pre-determined @ compile time

classloaders powerful feature , provide lot of functionality, can down right confusion, way chain together

you might find...

of help


Comments

Popular posts from this blog

java - Intellij Synchronizing output directories .. -

git - Initial Commit: "fatal: could not create leading directories of ..." -