Does this two Java statement lookup the class in the same way?
this.getClass().getClassLoader().loadClass("Foo");
and
Class.forName("Foo");
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
They’re different: even though they use the same class loader (see
forName()documentation)loadClass()does not run static initializers whileforName()does.This is easily demonstrated with the following classes:
and
Running
ClassBpassing true toloadStuff()will display “ClassA static initializer” while running it passing false toloadStuff()doesn’t display anything.Of course, if you subsequently instantiate the loaded class its static initializer will be run if it has not yet been executed. In this case the difference between the two methods of loading a class is in the time when static initializers are run.