Fundamentals 9 min read

Understanding Java Reflection: Advantages, Disadvantages, and Practical Use Cases

This article explains Java's reflection mechanism, discusses its strengths and weaknesses, and demonstrates common scenarios such as JDBC connection setup and Spring framework bean loading with clear code examples, helping developers decide when to apply reflection in backend development.

Selected Java Interview Questions
Selected Java Interview Questions
Selected Java Interview Questions
Understanding Java Reflection: Advantages, Disadvantages, and Practical Use Cases

While maintaining a project the author needed to assign values to object fields without invoking setter methods that contain business logic, so they turned to Java's reflection mechanism and used the opportunity to study its concrete usages and trade‑offs.

Advantages and disadvantages

Reflection is likened to a "god mode" that can bypass normal access controls: if a class exists, its members can be accessed at runtime. This enables dynamic type resolution, supports polymorphism, and reduces coupling, making code more flexible. However, reflective calls incur significant performance overhead because the JVM must interpret the operations, making them slower than direct method invocations.

The main pros are runtime type checking and dynamic class loading, which increase flexibility; the main cons are the performance penalty associated with the extra interpretation steps.

Typical application scenarios

Reflection is rarely used directly in everyday code but underpins many frameworks and design patterns. Common examples include modular development, dynamic proxy patterns, and major frameworks such as Spring and Hibernate that rely on CGLIB‑based reflection.

JDBC database connection example

To establish a JDBC connection, the driver class is loaded via Class.forName(), then DriverManager.getConnection() is used, and finally the connection is closed.

public class ConnectionJDBC {
    /**
     * @param args
     */
    // Driver class configured in the classpath
    public static final String DBDRIVER = "com.mysql.jdbc.Driver";
    // Connection URL provided by the DB vendor
    public static final String DBURL = "jdbc:mysql://localhost:3306/test";
    // Database username
    public static final String DBUSER = "root";
    // Database password
    public static final String DBPASS = "";

    public static void main(String[] args) throws Exception {
        Connection con = null; // connection object
        Class.forName(DBDRIVER); // load driver via reflection
        con = DriverManager.getConnection(DBURL, DBUSER, DBPASS); // connect
        System.out.println(con);
        con.close(); // close connection
    }
}

Spring framework usage example

Spring loads bean definitions from XML, parses class names, creates Class objects via reflection, instantiates beans, and injects property values by invoking setter methods reflectively. This decouples configuration from code and allows changes without recompilation.

public class BeanFactory {
    private Map<String, Object> beanMap = new HashMap<String, Object>();
    /**
     * Initialize bean factory from an XML file.
     * @param xml xml configuration file
     */
    public void init(String xml) {
        try {
            SAXReader reader = new SAXReader();
            ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
            InputStream ins = classLoader.getResourceAsStream(xml);
            Document doc = reader.read(ins);
            Element root = doc.getRootElement();
            Element foo;
            for (Iterator i = root.elementIterator("bean"); i.hasNext();) {
                foo = (Element) i.next();
                Attribute id = foo.attribute("id");
                Attribute cls = foo.attribute("class");
                Class bean = Class.forName(cls.getText());
                java.beans.BeanInfo info = java.beans.Introspector.getBeanInfo(bean);
                java.beans.PropertyDescriptor pd[] = info.getPropertyDescriptors();
                Method mSet = null;
                Object obj = bean.newInstance();
                for (Iterator ite = foo.elementIterator("property"); ite.hasNext();) {
                    Element foo2 = (Element) ite.next();
                    Attribute name = foo2.attribute("name");
                    String value = null;
                    for (Iterator ite1 = foo2.elementIterator("value"); ite1.hasNext();) {
                        Element node = (Element) ite1.next();
                        value = node.getText();
                        break;
                    }
                    for (int k = 0; k < pd.length; k++) {
                        if (pd[k].getName().equalsIgnoreCase(name.getText())) {
                            mSet = pd[k].getWriteMethod();
                            mSet.invoke(obj, value);
                        }
                    }
                }
                beanMap.put(id.getText(), obj);
            }
        } catch (Exception e) {
            System.out.println(e.toString());
        }
    }
    // other codes
}

In summary, reflection provides powerful dynamic capabilities useful for framework development and certain runtime tasks, but developers should be aware of its performance impact and use it judiciously.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

BackendJavaprogrammingReflectionspringJDBC
Selected Java Interview Questions
Written by

Selected Java Interview Questions

A professional Java tech channel sharing common knowledge to help developers fill gaps. Follow us!

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.