Reflection vs Encapsulation – Stand Off in the Java Module System(2)

来源:互联网 发布:梦幻龙族2修改数据库 编辑:程序博客网 时间:2024/05/16 01:06

  神TM还有续集。。

 The Stand Off

 对质


  Inside the module system (let’s drop the saloon, I think you got the joke) reflection could only ever access code in exported packages. Packages internal to a module were off limits and this already caused quite a ruckus. But it still allowed to use reflection to access everything else in an exported package, like package-visible classes or private fields and methods – this was called deep reflection. In September rules got even stricter! Now deep reflection was forbidden as well and reflection was no more powerful than the statically typed code we would write otherwise: Only public types, methods, and fields in exported packages were accessible.

  在模块系统中(让我们忘了那可笑的Saloon英文名吧,这里不让发车)反射只可以访问当导出包(exports)中的代码。模块中的包被限制访问,这已经引起了一些骚动。但是我们依然可以通过反射访问到导出包(exports)中的其他内容,像是包可见类或者private声明的字段和方法。这被称为深反射。在九月这种规则被定义的更加严格。现在深反射也被禁止了,反射不会再比静态类型的代码更强力,相反的现在只有public声明的类型,方法和字段在导出包中可以被访问。


  All if this caused a lot of discussions of course – some heated, some amicable but all with the sense of utter importance.

  当然如果这导致了很多的讨论,不管是激烈的还是有好的,都具有极其重要的意义。


  Some (myself included) favor strong encapsulation, arguing that modules need a safe space in which they can organize their internals without the risk of other code easily depending on it. Examples I like to give are JUnit 4, where one big reason for the rewrite was that tools depended on implementation details, reflecting down to the level of private fields; and Unsafe, whose pending removal put a lot of pressure on a lot of libraries.

  一些人(包括我)赞成强封装, 他们认为在模块内部需要一块安全的空间,在这块空间中他们可以放心的组织模块的内部信息,而不用担心会被其他的代码轻易依赖的风险。举个例子的话我很喜欢说JUnit 4,重写它的一个重要原因就是JUnit使用的一些工具依赖了具体的实现,这些工具使用了反射来访问到私有的属性;强封装的不安全,是给很多移除依赖的工作增加了很大的压力。


  Others argue that the flexibility provided by reflection not only enables great usability for the many frameworks relying on it, where annotating some entities and dropping hibernate.jar onto the class path suffices to make things work. It also gives freedom to library users, who can use their dependencies the way they want, which might not always be the way the maintainers intended to. Here, Unsafe comes in as an example for the other side: Many libraries and frameworks that are now critical to the Java ecosystem were only feasible exactly because some hacks were possible without the JDK team’s approval.

  另外一些人则认为,反射提供的灵活性不仅为许多框架的高度的可用性,例如在实体上加上注解,并将hibernate.jar放到classpath中就能够让一切正常运作。 它同样给库的使用者提供了自由,他们可以用他们想要的方式使用依赖的对象,尽管这种使用方式可能不是开发者的本意。反射这里,不安全的例子来自另外一面:当前Java生态系统中很多的重要的库和框架也仅仅是可用,因为一些骇客很有可能没有JDK团队的许可(感觉没读懂作者的原意,求大神们抬一手- -)


  Even though I tend towards encapsulation, I see the other arguments’ validity as well. So what to do? What choices to developers have besides encapsulating their internals and giving up on reflection?

  虽然我更倾向于封装,但是我也清楚其他观点的正确性。 所以该怎么做呢?除了封装内部和放弃反射之外,开发者还能怎么选择?

  这次就到这了,天国的第三集。

0 0
原创粉丝点击