Why reflection is used in this situation

Viewed 9532

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?

3 Answers

In this particular example, it looks like reflection is being used as a way ensure that the class (org.apache.catalina.startup.Catalina) is not loaded and initialized too early.

Is it still necessary to use reflection?

It is not clear that this (delayed loading) could not be done some other way.

And indeed, this is not sufficient to ensure that delayed loading happens. (If this classes identifier was used somewhere else, that could trigger premature loading.)


There are more "modern" approaches to this kind of problem; e.g. Spring's dependency injection. But the Tomcat codebase predates these innovations by may years. (And the principle of "if it ain't broken, don't fix it" applies.)

Related