Java反射機制的缺點

來源:互聯網
上載者:User

譯自官方指南(Tutorial):

http://docs.oracle.com/javase/tutorial/reflect/index.html

反射的用途 Uses of Reflection

Reflection is commonly used by programs which require the ability to examine or modify the runtime behavior of applications running in the Java
virtual machine. This is a relatively advanced feature and should be used only by developers who have a strong grasp of the fundamentals of the language. With that caveat in mind, reflection is a powerful technique and can enable applications to perform operations
which would otherwise be impossible.

反射被廣泛地用於那些需要在運行時檢測或修改程式行為的程式中。這是一個相對進階的特性,只有那些語言基礎非常紮實的開發人員才應該使用它。如果能把這句警示時刻放在心裡,那麼反射機制就會成為一項強大的技術,可以讓應用程式做一些幾乎不可能做到的事情。

反射的缺點 Drawbacks of Reflection

Reflection is powerful, but should not be used indiscriminately. If it is possible to perform an operation without using reflection, then it
is preferable to avoid using it. The following concerns should be kept in mind when accessing code via reflection.

儘管反射非常強大,但也不能濫用。如果一個功能可以不用反射完成,那麼最好就不用。在我們使用反射技術時,下面幾條內容應該牢記於心:

效能第一 Performance Overhead
Because reflection involves types that are dynamically resolved, certain Java virtual machine optimizations can not be performed. Consequently,
reflective operations have slower performance than their non-reflective counterparts, and should be avoided in sections of code which are called frequently in performance-sensitive applications.
反射包括了一些動態類型,所以JVM無法對這些代碼進行最佳化。因此,反射操作的效率要比那些非反射操作低得多。我們應該避免在經常被 執行的代碼或對效能要求很高的程式中使用反射。
安全限制 Security Restrictions
Reflection requires a runtime permission which may not be present when running under a security manager. This is in an important consideration for code which has to run in a restricted security context,
such as in an Applet.
使用反射技術要求程式必須在一個沒有安全限制的環境中運行。如果一個程式必須在有安全限制的環境中運行,如Applet,那麼這就是個問題了。。
內部暴露 Exposure of Internals
Since reflection allows code to perform operations that would be illegal in non-reflective code, such as accessing private fields and methods, the use of reflection can result in unexpected
side-effects, which may render code dysfunctional and may destroy portability. Reflective code breaks abstractions and therefore may change behavior with upgrades of the platform.
由於反射允許代碼執行一些在正常情況下不被允許的操作(比如訪問私人的屬性和方法),所以使用反射可能會導致意料之外的副作用--代碼有功能上的錯誤,降低可移植性。反射代碼破壞了抽象性,因此當平台發生改變的時候,代碼的行為就有可能也隨著變化。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.