基于反射的实例化
什么时候需要基于反射的实例化而不是通过 new 进行正常实例化?这是一个好的软件工程实践吗?
When is it desired to have reflection based instantiation instead of a normal instantiation via a new? Is it a good software engineering practice?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当您的程序无法在编译时访问该类时,例如,在运行时在库中提供该类,并且将类的名称和库的路径提供给您的程序作为配置的一部分。为您的程序独立开发的插件是基于反射的实例化的良好候选者。在其他情况下,基于反射的实例化也可能是理想的:例如,当您知道所需的类,但您事先不知道希望它们以何种方式连接时。构建表达式树就是这种情况的一个例子。
Using reflection is required when your program does not have a compile-time access to the class, for example, when the class is provided in a library at run-time, and the name of the class and the path to the library are provided to your program as part of configuration. Independently developed plug-ins for your program are good candidates for reflection-based instantiation. Reflection-based instantiation may be desirable in other cases as well: for example, when you know which classes you want, but you do not know ahead of time in what way you want them to be connected. Constructing expression trees is an example of this situation.