那么它们的目的是什么

那么它们的目的是什么

本文介绍了如果可以通过反射绕过访问修饰符,那么它们的目的是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我了解使用访问修饰符是编写Java(或大多数)代码时的重要实践,但是由于您可以使用反射来绕过这些修饰符,因此不是有效地使访问冗余变得多余了吗?

I understand that using access modifiers is an important practice when writing Java (or most) code, but isn't it effectively made redundant by the fact that you can bypass these modifiers using reflection?

例如,如果我想通过将对象敏感变量设置为私有并提供访问器方法来保护它们,那么仍然可以轻松地使用反射来进入并绕过该对象,并可能设置不安全的值.为什么Java提供访问修饰符,然后提供绕过它们的工具?不使用它们似乎会更容易.

For example, if I want to protect my objects sensitive variables by setting them to private and providing accessor methods, someone can still easily come in and bypass this using reflection, and potentially set unsafe values. Why does Java provide access modifiers, and then a tool to bypass them? It seems it would just be easier to not use either.

推荐答案

访问修饰符的一个重要目的是构造代码,并帮助该代码的用户正确有效地理解和使用它.这与充当防篡改安全机制不同.因此,同时具有访问修饰符和反射并不矛盾.代码编写者可以使用访问修饰符表达其意图,而出于任何原因需要绕过它们的代码可以通过通常的风险和含义来做到这一点.

A significant purpose of access modifiers is to structure the code and help users of that code understand and use it effectively and correctly. This is different from serving as a tamper-proof security mechanism. For this reason, it is not contradictory to have both access modifiers and reflection. Writers of the code can express their intent using access modifiers, and code that needs to bypass them, for whatever reason, can do this with the usual risks and implications.

这篇关于如果可以通过反射绕过访问修饰符,那么它们的目的是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 17:02