使用ButterKnife公开成员变量 [英] Exposing Member Variables with ButterKnife

查看:228
本文介绍了使用ButterKnife公开成员变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个有趣的问题,我正在使用ButterKnife,但我发现您不能在私有方法中使用,因为ButterKnife创建了使用它们的类. 这不违反封装原理吗?我的意思是,那么您的变量也将暴露给其他类,不是吗?

Curious question, I'm using ButterKnife and I just discovered you can't use in private methods because ButterKnife creates classes that use them. Doesn't that violates the principle of encapsulation? I mean, then your variables will be exposed to other classes as well, no?

推荐答案

您完全正确,使用Butterknife违反了封装原理.

You are totally right, using Butterknife violates the principle of encapsulation.

Butterknife使用其自身生成的代码来执行视图查找.而且这些查找是在单独的类(-es)中完成的,因此这些字段不能是私有的.

Butterknife uses its own generated code to perform view look-ups. And those look-ups are done in separate class(-es) hence the fields cannot be private.

报价:

生成的代码存在于该类之外的一个类中,因此 字段实际上是在类之外访问的,因此不是 私人的.如果您看到其他正在访问私有的生成代码 字段,它使用反射来绕过私有访问 限制,这意味着您有一些看起来很私密但属于 实际上是在课程之外访问的.

The generated code exists in a class outside of this class, thus the fields are truly being accessed outside of the class, hence not private. If you see other generated code that is accessing private fields, it is using reflection to by-pass the private access restriction, which means you have fields that look private but are actually being accessed outside of the class.

与反射查找相比,使用反射不仅在引擎盖下是同一件事,而且显着更慢.

Using reflection would not only be the same thing under the hood but also significantly slower compared to view look-ups.


无论如何,那些使用Butterknife来执行视图绑定的类不应在负责同一事务的类之外的任何地方初始化(即,视图绑定),因此违反封装并不是什么大问题.例如:Activities可以具有Fragments的实例,Fragments/Activities可以具有RecyclerViewAdapters的实例,因为所有这些都负责视图绑定,但是ViewModel (MVVM体系结构)用于该示例通常不应具有Fragment/Activity或任何View的实例,因为它与视图绑定无关.


Anyway, those classes that use Butterknife to perform view binding should not be initialized anywhere apart of classes that are responsible for the same thing (view binding, that is) so violating encapsulation is not a big deal. For example: Activities can have instances of Fragments, Fragments/Activities can have instances of RecyclerViewAdapters because all of these are responsible for view binding, but ViewModel (MVVM architecture) for example should not have an instance of Fragment/Activity or any View in general because it has nothing to do with view binding.

祝你好运. :)

这篇关于使用ButterKnife公开成员变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆