Today, I am looking the source code of tomcat
in the Bootstrap.init()
method, I found it used reflection to create an instance of org.apache.catalina.startup.Catalina
, and use invoke()
to set the ClassLoader
Like the following code
Class<?> startupClass = catalinaLoader.loadClass("org.apache.catalina.startup.Catalina");
Object startupInstance = startupClass.getConstructor().newInstance();
String methodName = "setParentClassLoader";
Method method =
startupInstance.getClass().getMethod(methodName, paramTypes);
method.invoke(startupInstance, paramValues);
I found that many frameworks use reflections to create an instance, even though the class and method can be determined
Just like the above code, use String
to determine the target.
Is it still necessary to use reflection?
Yes.
For example, Spring uses <bean>
definitions as such
<bean id="someId" class="com.foopack.Foo">
<property name="someField" value="someValue" />
</bean>
When the Spring context processes this <bean>
element, it will use Class.forName(String)
with the argument as com.foopack.Foo
to instantiate that Class (Class#newInstance()
or get a Constructor
, depending). It will then again use reflection to get the appropriate setter for the <property>
element and set its value to the specified value
.
Junit also uses reflection to get a set of @Test
annotated methods to invoke. To do this, it needs to get a Class
instance.
Servlet based web applications also use reflection to instantiate Servlet
, Filter
, and the different types of Listeners classes. For example, you would have
<servlet>
<servlet-name>YourServlet</servlet-name>
<servlet-class>com.servlets.YourServlet</servlet-class>
<servlet>
and the container would take that fully qualified class name, com.servlets.YourServlet
, and instantiate and register it.
JSON parser/generator libraries also use reflection. For example, with Gson
, given a class like
class Foo {
private String name = "FOOOO";
}
and an instance like this
Foo foo = new Foo();
you would serialize it like so
Gson gson = new Gson();
String json = gson.toJson(foo);
Gson would then call getClass()
on the instance foo
, get a set of the Field
instances of that Class
, iterate over the set, and serialize the values of the fields to a JSON format.
There are several ways to get Class
object. Class.forName
is one of them. Very often it is obj.getClass().
As for Spring it uses ClassLoader.loadClass
when loading beans, see org.springframework.util.ClassUtils
in spring-core
module.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With