In Spring, although reflection is used heavily within the framework to create bean instances, we usually do not need to use reflection directly to create beans. Spring containers automatically complete the creation and management of beans based on bean definitions.
However, understanding how to create bean instances using reflection helps us gain a deeper understanding of how Spring works, and in some special cases (e.g., customizationFactoryBean
, write test code, create objects dynamically, etc.) to perform more flexible operations.
Here are a few ways to create bean instances using reflection:
1. Use () (only for the non-argument constructor):
This is the easiest way, but only for havingpublic parameterless constructorclass.Deprecated:Starting with Java 9,()
Methods have been marked out as outdated, recommendedgetDeclaredConstructor().newInstance()
。
public class MyBean { public MyBean() { ("MyBean created using default constructor."); } } public class CreateBeanWithReflection { public static void main(String[] args) throws Exception { // Use () (Obsolete) Class<MyBean> clazz = ; MyBean myBean = (); // Create MyBean instance } }
2. Use () (recommended):
- This is a more flexible way to use for classes with any type of constructor (including private constructors, constructors with arguments).
- Need to get it first
Constructor
object, then call itnewInstance()
method.
import ; public class MyBean { private String name; private int age; // No parameter constructor public MyBean() { ("MyBean created using default constructor."); } // Constructor with parameters public MyBean(String name, int age) { ("MyBean created using parameterized constructor."); = name; = age; } // Private constructor private MyBean(String name){ ("MyBean created using private constructor"); = name; } } public class CreateBeanWithReflection { public static void main(String[] args) throws Exception { Class<MyBean> clazz = ; // 1. Use parameterless constructor Constructor<MyBean> defaultConstructor = (); MyBean myBean1 = (); // 2. Use constructors with parameters Constructor<MyBean> parameterizedConstructor = (, ); MyBean myBean2 = ("John", 30); // 3. Use private constructors Constructor<MyBean> privateConstructor = (); (true); // Set access to private constructor MyBean myBean3 = ("Private Bean"); } }
3. Use the Factory Method:
- If the bean is created through a factory method, the factory method can be called using reflection.
-
Static factory method:
- Obtain factory
Class
Object. - Obtain factory method
Method
Object. - Call
(null, ...)
, the first parameter isnull
, means to call a static method.
- Obtain factory
-
Example factory method:
- Create an instance of the factory class.
- Obtain factory method
Method
Object. - Call
(factoryInstance, ...)
, the first parameter is an instance of the factory class.
import ; public class MyBean { private String message; private MyBean(String message) { = message; } // Static factory method public static MyBean createInstance(String message) { return new MyBean(message); } public String getMessage(){ return message; } } //Factorypublic class MyBeanFactory{ public MyBean createMyBean(String message){ return new MyBean(message); } } public class CreateBeanWithReflection { public static void main(String[] args) throws Exception { // 1. Use the static factory method Class<MyBean> clazz = ; Method staticFactoryMethod = ("createInstance", ); MyBean myBean1 = (MyBean) (null, "Hello from static factory method"); (()); // 2. Use the instance factory method MyBeanFactory factory = new MyBeanFactory(); // Create a factory instance Method instanceFactoryMethod = ("createMyBean", ); MyBean myBean2 = (MyBean) (factory, "Hello from instance factory method"); (()); } }
4. Use BeanUtils (Spring Framework):
- Spring's
BeanUtils
Classes provide some convenient ways to create bean instances and operate bean properties. ()
import ; public class MyBean { public MyBean() { ("MyBean created using default constructor."); } } public class CreateBeanWithReflection { public static void main(String[] args) throws Exception { // use () MyBean myBean = (); } }
Notes:
-
Exception handling:The reflection operation may throw various exceptions (
NoSuchMethodException
、IllegalAccessException
、InstantiationException
、InvocationTargetException
etc.), appropriate exception handling is required. - performance:Reflection operations are usually slower than calling constructors or methods directly. If performance is critical, unnecessary reflections should be avoided.
-
Security:If you need to access a private constructor or method, you need to use
setAccessible(true)
, but this will destroy the packaging and should be used with caution. - Type Safety:Reflection operations are runtime and may cause type safety issues.
Here's how to create a bean instance in Spring using reflection? That’s all about the article. For more related Spring to create bean examples using reflection, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!