java - Class.forname("name").newInstance() vs name.class.newInstance : Difference in usage perspective -


i start example: have class classload.loadable .

package classload;  public class loadable {     static{         system.out.println("loaded already.....");     }     public loadable(){         system.out.println("now created.....");     } } 

which loaded , created instance in following 2 ways.

first:

 public static void main(string[] args) throws exception {                 system.out.println("starting .....");                 class.forname("classload.loadable").newinstance();             } 

second:

 public static void main(string[] args) throws exception {                 system.out.println("starting .....");                  classload.loadable.class.newinstance();             } 

both gives same output expected(since class.forname returns same class object):

starting ..... loaded already..... created..... 

i want know scenarios use class.forname , whereever may use .class object directly

the simplest solution use

new loadable(); 

if class know @ compile time , expect available @ runtime. note: throw noclassdeferror @ runtime if not available.

if not sure available runtime, might use

class.forname("classload.loadable").newinstance(); 

as clearer exceptions thrown.

the problem with

classload.loadable.class.newinstance() 

is it's not particularly useful in either context.

note: class.newinstance() has known issue throw checked exceptions don't know about. i.e. if constructor throws checked exception won't wrapped , compiler can't tell thrown.


Comments

Popular posts from this blog

resizing Telegram inline keyboard -

command line - How can a Python program background itself? -

php - "cURL error 28: Resolving timed out" on Wordpress on Azure App Service on Linux -