我知道反射的作用,但我想知道在什么具体情况下我们可以使用它。就像,使用反射我们可以知道该类是否包含指定的方法。我也想知道这种需求在实际场景中可以实现吗?使用反射对应用程序性能有什么影响吗?
最佳答案
反射的性能之前已在此处回答过 Java Reflection Performance
但是快速总结一下:
引用Java's documentation on reflection :
Because reflection involves types that are dynamically resolved, certain Java virtual machine optimizations can not be performed. Consequently, reflective operations have slower performance than their non-reflective counterparts, and should be avoided in sections of code which are called frequently in performance-sensitive applications.
如果您无法直接访问某些 API(因为该 API 未向公众公开)或者您想要自动化某些操作(单元测试或其他操作),那么反射会很有用。
关于java - Java中的反射如何影响应用程序的性能以及哪些场景可以使用反射?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25906480/