Home >Java >javaTutorial >Item Prefer interfaces over reflection
Reflection in Java (java.lang.reflect):
Through reflection, it is possible:
Disadvantages of Reflection:
Loss of compile-time type checking:
Heavy and verbose code:
Reflection requires more complex and less readable code.
Example:
Method method = obj.getClass().getMethod("methodName"); method.invoke(obj, args);
Underperformance:
Applications of Reflection:
Limited use of reflection:
Suggested technique: Use reflection only to instantiate unknown classes at compile time, and reference these instances through known interfaces or superclasses.
Example:
Program that creates instances of Set, specified by the command line:
Class extends Set<string>> cl = (Class extends Set<string>>) Class.forName(args[0]); Constructor extends Set<string>> cons = cl.getDeclaredConstructor(); Set<string> s = cons.newInstance(); for (int i = 1; i <p><strong>Disadvantages illustrated in the example:</strong><br> <strong>Runtime Exceptions:</strong></p> <ul> <li>The example can generate up to six different exceptions at run time.</li> <li>These exceptions would be caught at compile time if reflection were not used.</li> </ul> <p><strong>Complexity and verbosity:</strong></p> <ul> <li>The example requires 25 lines of code to instantiate a class from its name, while a direct constructor call would be done in just one line.</li> </ul> <p><strong>Unverified cast warning:</strong></p> <ul> <li>In the example, there is a legitimate warning of unchecked cast, as the class specified on the command line may not be an implementation of Set.</li> </ul> <p><strong>Legitimate use of reflection:</strong></p> <ul> <li>Dynamic dependencies: when a class, method or field may not exist at run time.</li> <li>Example: You can use reflection to support multiple versions of a package without breaking backwards compatibility.</li> </ul> <p>Conclusion:<br> Reflection is powerful, but it has many disadvantages.<br> Whenever possible, use reflection only to instantiate objects and access them through interfaces or superclasses known at compile time.</p> <p>Example from the book:<br> <img src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/article/000/000/000/172981386629875.jpg?x-oss-process=image/resize,p_40" class="lazy" alt="Item Dê preferência às interfaces em vez da reflexão"></p> </string></string></string></string>
The above is the detailed content of Item Prefer interfaces over reflection. For more information, please follow other related articles on the PHP Chinese website!