Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: creating objects based on string using class.forname.newinstance vs if statements

Tags:

java

I came upon class.forname.newInstance while searching creating objects by String. I know using the former method takes longer time than using keyword new, but how much longer? If I want to create an instance of the 100 classes I have based on the value of a String, how much longer would it take? Run time wise is it better to do just 100 if statements(I don't mind doing that, really..)?

like image 321
Pear Avatar asked Sep 03 '26 20:09

Pear


1 Answers

Using new operator is very fast and optimized because it performs compile time construction.

Class.forName().newInstance() performs dynamic construction which is much slower than new operator because type of object is not readily known during run time and certain Java virtual machine optimizations can not be performed.

Also reflection has security restrictions as they always require run time permission when running under security manager I highly dont recommend to use reflection unless you have specific reason to do that .

To answer your exact question , If you prefer Class.forName().newInstance() will cost you 4 times more (Atleast in my system when i tested the code for 100 operations) than the new operator.

Avoid using reflection

like image 71
arunprakashpj Avatar answered Sep 06 '26 11:09

arunprakashpj



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!