Java:什么场景要求使用反射? [英] Java: What scenarios call for the use of reflection?
问题描述
因此,通过阅读一些文章,我得到的消息是能够实时修改字段并将值设置为类而无需重新编译。
So from reading some of the articles, the message i got out of it was being able to modify fields and set values to classes in real time without recompiling.
那么有可能对第三方java库创建的类没有源代码可用/是否可以使用反射在运行时修改类实例?
so is it possible to do this to 3rd party java library created classes which no source code is available / is it possible to use reflection to modify class instances on run time?
在其他场景中常用的反射是什么?
in what other scenarios is reflection commonly used?
我试图理解反射是如何适用的。
I am trying to understand how reflection can be applicable.
推荐答案
每次在运行时处理字符串并希望将该字符串的一部分视为该语言中的标识符。
Any time you're dealing with a string at runtime and want to treat part of that string as an identifier in the language.
- 远程过程调用 - 将通过网络接收的消息的一部分视为方法名称。
- 序列化和反序列化 - 将字段名称转换为字符串,以便您可以将对象的字段写入流中,然后将其转换回对象。
- Objec t-relational mappings - 维护对象中的字段与数据库中的列之间的关系。
- 与动态类型脚本语言的接口 - 将脚本语言生成的字符串值转换为引用对象上的字段或方法。
- Remote procedure calling -- treat part of a message received over the network as a method name.
- Serialization and deserialization -- convert field names to string so you can write the object's fields to a stream and later convert it back into an object.
- Object-relational mappings -- maintain a relationship between fields in an object and columns in a database.
- Interfaces with dynamically typed scripting languages -- turn a string value produced by a scripting language into a reference to a field or method on an object.
它还可用于允许使用该语言模拟语言功能。
考虑命令行 java com.example.MyClass
,它将字符串转换为类名。这不需要反射,因为 java
可执行文件可以将 .class
文件转换为代码,但没有反映它将无法编写 java com.example.Wrapper com.example.MyClass
其中 Wrapper
委托其参数为in:
It can also be used to allow language features to be emulated in the language.
Consider the command line java com.example.MyClass
which turns a string into a class name. This doesn't require reflection, because the java
executable can turn a .class
file into code, but without reflection it would not be able to write java com.example.Wrapper com.example.MyClass
where Wrapper
delegates to its argument as in:
class Wrapper {
public static void main(String... argv) throws Exception {
// Do some initialization or other work.
Class<?> delegate = Class.forName(argv[0]);
Method main = delegate.getMethod("main", String[].class);
main.apply(null, Arrays.asList(argv).subList(1, argv.length).toArray(argv));
}
}
这篇关于Java:什么场景要求使用反射?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!