android - 使用 ButterKnife 公开成员变量

标签 android annotations butterknife

奇怪的问题,我正在使用 ButterKnife,我刚刚发现您不能在私有(private)方法中使用,因为 ButterKnife 创建了使用它们的类。 这不是违反了封装原则吗?我的意思是,那么你的变量也会暴露给其他类,不是吗?

最佳答案

你完全正确,使用Butterknife违反了封装原则。


Butterknife 使用自己生成的代码来执行 View 查找。并且这些查找是在单独的类(-es)中完成的,因此这些字段不能是私有(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.

使用反射不仅在引擎盖下是一回事,而且与 View 查找相比速度要慢得多。


无论如何,那些使用 Butterknife 执行 View 绑定(bind)的类不应该在负责相同事情(即 View 绑定(bind))的类之外的任何地方初始化,因此违反封装不是什么大问题。例如:Activities 可以有 Fragments 的实例,Fragments/Activities 可以有 RecyclerViewAdapters 的实例,因为所有这些负责 View 绑定(bind),但是 ViewModel (MVVM 架构) 例如不应该有 Fragment/Activity 或任何 View 的实例 一般是因为它与 View 绑定(bind)无关。


祝你好运。 :)

关于android - 使用 ButterKnife 公开成员变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50901495/

相关文章:

android - 如何获取 Intent 过滤器 MimeType

java - Hibernate 自定义查找器 SQL 查询不返回 OneToMany 关系

android - 在 Android 中使用 Butterknife

java - ListView 适配器不工作,未调用 getView。

android - 无法更改 MotionLayout 中 TextInputLayout 的可见性

java - 何时调用标有@PostConstruct 的方法?

ios - 更改出列的注释 View 的图像会导致先前使用的图像短暂出现

java - Butterknife 不适用于适配器类

android - Butterknife 7.x 是否适用于 Kotlin M14?

android - 谷歌地图自定义样式 - 饱和度、亮度不起作用