0

我试图弄清楚为什么人们说这是防止访问您不想要的类文件的好方法,但我不能只使用反射来访问类吗?混淆是不是更好地防止未经授权的访问,因为即使他们使用反射,也没有人知道您的代码做了什么?

4

3 回答 3

1

The point of encapsulation is to prevent access to your implementation internal classes for the sake of cleaner code, not to technically prevent users of your class from accessing instances using reflection, or decompiling it.

For example, if you have an HTTP client, you should encapsulate the streams and buffers you use, and only expose the request and response to the actual user of your class. This is designed so your--and their--code is cleaner, not so that they can never reflect on your class. Additionally, since the only API users are accessing is the external API, you are free to change the internals of your classes or code as much as you wish.

于 2015-02-27T23:41:47.510 回答
1

封装是一种与其他程序员交流他们应该和不应该对您的数据做什么的方式。他们总是可以规避这一点,但是通过稍微增加难度,您实际上告诉他们在访问封装数据时要格外小心,并警告他们您可能随时更改您的实现并破坏任何依赖它的代码。

封装不是保护您的代码和数据免受恶意访问的类似 DRM 的方法。

于 2015-02-27T23:45:13.003 回答
1

封装不是为了阻止对后端代码的访问,而是为了表示边界。它帮助程序员编写易于扩展修改的代码。从这里开始,诸如“关注点分离”之类的原则就会出现。

于 2015-02-28T00:10:15.087 回答