Java反射:运行时修改的含义是什么?

huangapple go评论78阅读模式
英文:

Java reflection : what modifying at runtime means?

问题

我正在学习Java反射API。我已经阅读了很多关于java.lang.reflect包的内容。但仍然有一些我不太理解的地方:使用内省,你可以在运行时修改对象。

基本上,你不需要内省/反射来做到这一点。通过一个简单的setter()方法,你也可以在运行时修改你的对象。使用简单的setter方法和使用反射之间有什么区别?在这两种情况下,你都可以达到相同的结果。

英文:

I'm learining Java reflection API. I have read a lot, use java.lang.reflect package.
But there is still something I don't understand : the idea that with introspection, you can modify objects at runtime.

Basically you do not need introspection/reflection to do that. With a simple setter() method, you can also modify your object at runtime. What's the difference between using simple setters or using reflection ? In both cases you can achieve the same result.

答案1

得分: 2

使用反射,您可以实例化对象并调用在编译时未知的方法。

想象一下,您有一个包含类名称的文本文件。您可以使用反射来加载和实例化该类,即使在编译程序时该文件不存在。

类似地,您可以使用它来构建诸如通用配置系统之类的东西,其中您可以根据某些配置文件创建对象并设置属性,而不是使用硬编码的调用(Spring 是实现这一目标的一种方式)。

英文:

With reflection you can instantiate objects and call methods that you didn't know about at compile time.

Imagine you had a text file that contained the name of a class. You can use reflection to load and instantiate that class, even if that file didn't exist when your program was compiled.

Similarly, you can use it to build things like generic configuration systems where you create objects and set properties based on some configuration files instead of using hard-coded calls (Spring is one way this can go).

huangapple
  • 本文由 发表于 2020年7月30日 06:19:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/63163271.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定