I need to create objects dynamically. I use Spring to create a map of class names. Now I can use
Spring ApplicationContext.getbean(className)
or
Java Class.forName(className).newInstance().
Which method is more efficient?
Thanks you.
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.
If the spring bean is a prototype-scoped bean, Spring will have to instantiate it with reflection, and will thus have to do what your second snippet does. But asking the Spring context to get a bean doesn’t just get you a new instance of a class. It returns a Spring bean, on which you could have aspects applied (security, transactional, etc.), dependencies injected, etc.
You shouldn’t choose what to call based on performance, but on what you want to get. Anyway, the cost of both calls is probably negligible compared to the rest of what your app does (network calls, database queries, etc.)