溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Java 反射機制的缺點有哪些

發(fā)布時間:2021-01-13 14:49:20 來源:億速云 閱讀:450 作者:Leah 欄目:編程語言

本篇文章給大家分享的是有關(guān)Java 反射機制的缺點有哪些,小編覺得挺實用的,因此分享給大家學(xué)習(xí),希望大家閱讀完這篇文章后可以有所收獲,話不多說,跟著小編一起來看看吧。

反射的用途 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.
反射被廣泛地用于那些需要在運行時檢測或修改程序行為的程序中。這是一個相對高級
的特性,只有那些語言基礎(chǔ)非常扎實的開發(fā)者才應(yīng)該使用它。如果能把這句警示時刻放在心
里,那么反射機制就會成為一項強大的技術(shù),可以讓應(yīng)用程序做一些幾乎不可能做到的事情。

反射的缺點 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.
盡管反射非常強大,但也不能濫用。如果一個功能可以不用反射完成,那么最好就不用。
在我們使用反射技術(shù)時,下面幾條內(nèi)容應(yīng)該牢記于心:

性能第一 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.
反射包括了一些動態(tài)類型,所以 JVM 無法對這些代碼進行優(yōu)化。因此,反射操作的效
率要比那些非反射操作低得多。我們應(yīng)該避免在經(jīng)常被 執(zhí)行的代碼或?qū)π阅芤蠛芨叩某?
序中使用反射。

安全限制 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.
使用反射技術(shù)要求程序必須在一個沒有安全限制的環(huán)境中運行。如果一個程序必須在有
安全限制的環(huán)境中運行,如 Applet,那么這就是個問題了。

內(nèi)部暴露 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.
由于反射允許代碼執(zhí)行一些在正常情況下不被允許的操作(比如訪問私有的屬性和方
法),所以使用反射可能會導(dǎo)致意料之外的副作用--代碼有功能上的錯誤,降低可移植性。
反射代碼破壞了抽象性,因此當(dāng)平臺發(fā)生改變的時候,代碼的行為就有可能也隨著變化。

以上就是Java 反射機制的缺點有哪些,小編相信有部分知識點可能是我們?nèi)粘9ぷ鲿姷交蛴玫降摹OM隳芡ㄟ^這篇文章學(xué)到更多知識。更多詳情敬請關(guān)注億速云行業(yè)資訊頻道。

向AI問一下細節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI