官方指南(Tutorial ) :
反射的用途Uses of Reflection
reflectioniscommonlyusedbyprogramswhichrequiretheabilitytoexamineormodifytheruntimebehaviorofapplicationsrunninginthejava
virtual machine.thisisarelativelyadvancedfeatureandshouldbeusedonlybydeveloperswhohaveastrongggraspofthefundamentalsofthelanguthelanguranguthed mind,reflectionisapowerfultechniqueandcanenableapplicationstoperformoperations
which would otherwise be impossible。
反射广泛用于需要在运行时检测或修改程序行为的程序中。 这是比较高级的特性,只有语言基础非常扎实的开发者才应该使用它。 如果您始终牢记此警告,则反射机制将是一项强大的技术,可以让APP应用程序做几乎不可能的事情。
反射的缺点Drawbacks of Reflection
Reflection is powerful,butshouldnotbeusedindiscriminately.ifitispossibletoperformanoperationwithoutusingreflection,then it
ispreferabletoavoidusingit.thefollowingconcernsshouldbekeptinmindwhenaccessingcodeviareflection。
反射非常强大,但不能滥用。 如果一个功能可以在没有反射的情况下完成,最好不要使用。 使用反射技术时,必须牢记以下几点:
性能第一的performanceoverheadbecausereflectioninvolvestypesthataredynamicallyresolved,certainjavavirtualmachineoptimizationationed
reflectiveoperationshaveslowerperformancethantheirnon-reflective counterparts, 因为andshouldbeavoidedinsectionsofcodewhicharecalledfrequentlyinperformance-sensitive applications .的反射包含动态类型,所以JVM是这些核心因此,反射操作的效率比非反射操作低得多。 应该避免在经常运行的代码或需要性能的程序中进行反射。 安全限制securityrestrictionsreflectionrequiresaruntimepermissionwhichmaynotbepresentwhenrunningunderasecuritymanager.thisinanionimpppp onforcodewhichhastoruninarestrictedsecuritycontext,
such as in an Applet .要使用反射技术,程序必须在安全、不受限制的环境中运行。 如果需要在applet这样有安全限制的环境中运行程序,这就成了问题。 内部暴露exposureofinternalssincereflectionallowscodetoperformoperationsthatwouldbeillegalinnon-reflective code,suchasacessingpringprion
side-effects, whichmayrendercodedysfunctionalandmaydestroyportability.reflectivecodebreaksabstractionsandthereforemaychangebehaviorwithupggity 使用反射可能会产生意外的副作用,因为代码可以执行通常不允许的操作,如访问私有属性和方法。 代码中存在功能性错误,会降低可移植性。 由于反射代码会破坏抽象性,因此平台改变时代码的行为也可能发生变化。