除了逆向工程之外,反射真的有用吗?
Java 和 PHP 等语言支持反射,允许对象提供有关自身的元数据。是否存在任何合法的用例,您需要能够执行一些操作,例如询问对象在逆向工程领域之外有哪些方法?这些用例中的任何一个现在都已实际实施吗?
Languages such as Java and PHP support reflection, which allows objects to provide metadata about themselves. Are there any legitimate use cases where you would need to be able to do something like ask an object what methods it has outside of the realm of reverse engineering? Are any of those use cases actually implemented today?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
反射在 Java 中被框架广泛使用,这些框架在运行时动态地与其他代码一起操作。如果没有反射,代码之间的所有链接都必须在编译时完成(静态)。
例如,任何有用的插件框架(OSGi、JSPF、JPF)都会利用反射。任何注入框架(Spring、Guice 等)都利用反射。
每当您想要编写一段与另一段代码交互的代码时,在编译时该代码段不可用,反射就是 Java 中的前进方向。
然而,这最好留给框架,并且应该被封装。
Reflection is used extensively in Java by frameworks which are leveraged at runtime to operate with other code dynamically. Without reflection, all links between code must be done at compile time (statically).
So, for example, any useful plug-in framework (OSGi, JSPF, JPF), leverages Reflection. Any injection framework (Spring, Guice, etc) leverages Reflection.
Any time you want to write a piece of code that will interact with another piece of code without having that piece of code available when compiling, Reflection is the way forward in Java.
However, this is best left to frameworks and should be encapsulated.
当然有很好的用例。例如,获取开发人员提供的元数据。 Java API 越来越多地使用注释来提供有关方法/字段/类及其使用的信息。就像输入验证、绑定到数据表示一样......您可以在编译时使用这些来生成元数据描述符并使用它们,但在运行时执行此操作将需要反射。即使您使用元数据描述符,它们最终也会包含需要通过反射访问的类、方法和字段名称等内容。
另一个用例:动态语言。以 Ruby 为例……它允许您在尝试调用某个方法之前预先检查对象是否会响应该方法名称。类似这样的事情需要反思。
或者当必须从外部编译代码提供类或方法名称时怎么样,例如选择某些 API 的实现时。这只是一些文字。查找它的解决方案归结为反思。
There certainly are good use cases. For example, obtaining developer-provided metadata. Java APIs are increasingly using annotations to provide info about methods/fields/classes and their use. Like input validation, binding to data representations... You could use these at compile-time to generate metadata descriptors and use those, but to do it at runtime would require reflection. Even if you used the metadata descriptors, they'd end up containing things like class, method and field names that'd need to be accessed via reflection.
Another use case: dynamic languages. Take Ruby... It allows you to check up-front whether an object would respond to a method name before trying to call that method. Something like that requires reflection.
Or how about when a class or method name must be provided from outside compiled code, like when selecting an implementation of some API. That's just gonna be a bit of text. Looking up what it resolves to comes down to reflection.
Spring 或 Hibernate 等框架广泛使用反射来检查类并查看注释。
Frameworks like Spring or Hibernate make extensive use of reflection to inspect a class and see the annotations.
用于调试、序列化、日志记录、测试的框架...
Frameworks for debugging, serialization, logging, testing...