Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How reflection is used in framework? [closed]

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?

like image 449
Ryan Avatar asked Nov 27 '22 17:11

Ryan


2 Answers

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.

like image 64
Sotirios Delimanolis Avatar answered Dec 09 '22 18:12

Sotirios Delimanolis


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.

like image 27
Evgeniy Dorofeev Avatar answered Dec 09 '22 18:12

Evgeniy Dorofeev