Home >Java >javaTutorial >How to Achieve the Equivalent of Java\'s Class.forName() in Python?
Python's Flexible Reflection: Equivalent to Java's Class.forName()
Python's reflection capabilities are significantly more versatile and user-friendly compared to Java's Class.forName(). While there may not be an exact direct equivalent, understanding Python's reflection mechanisms allows you to achieve similar functionality.
Python's Reflection Approach
Python's reflection utilizes several essential techniques:
Custom Function: get_class
To provide an equivalent functionality to Class.forName(), the following Python function can be utilized:
<code class="python">def get_class(kls): parts = kls.split('.') module = '.'.join(parts[:-1]) m = __import__(module) for comp in parts[1:]: m = getattr(m, comp) return m</code>
Usage Example
This function enables you to obtain a class reference from its fully qualified name:
<code class="python">>>> D = get_class("datetime.datetime") >>> D <type 'datetime.datetime'> >>> D.now() datetime.datetime(2009, 1, 17, 2, 15, 58, 883000)</code>
How it Works
Conclusion
Python's reflection offers a powerful and flexible way to manipulate classes and objects. While it differs from Java's Class.forName(), it provides a more adaptable and feature-rich approach to achieve similar goals.
The above is the detailed content of How to Achieve the Equivalent of Java\'s Class.forName() in Python?. For more information, please follow other related articles on the PHP Chinese website!