浅谈Java编程中的synthetic关键字
javasynthetic关键字。有synthetic标记的field和method是class内部使用的,正常的源代码里不会出现syntheticfield。小颖编译工具用的就是jad.所有反编译工具都不能保证完全正确地反编译class。所以你不能要求太多。
下面我给大家介绍一下synthetic
下面的例子是最常见的syntheticfield
Java代码
classparent{ publicvoidfoo(){ } classinner{ inner(){ foo(); } } }
非static的innerclass里面都会有一个this$0的字段保存它的父对象。编译后的innerclass就像下面这样:
Java代码
classparent$inner{ syntheticparentthis$0; parent$inner(parentthis$0) { this.this$0=this$0; this$0.foo(); } }
所有父对象的非私有成员都通过this$0来访问。
还有许多用到synthetic的地方。比如使用了assert关键字的class会有一个syntheticstaticboolean$assertionsDisabled字段
使用了assert的地方
assertcondition;
在class里被编译成
Java代码
if(!$assertionsDisabled&&!condition){ thrownewAssertionError(); }
还有,在jvm里,所有class的私有成员都不允许在其他类里访问,包括它的innerclass。在java语言里innerclass是可以访问父类的私有成员的。在class里是用如下的方法实现的:
Java代码
classparent{ privateintvalue=0; syntheticstaticintaccess$000(parentobj) { returnvalue; } }
在innerclass里通过access$000来访问value字段。
synthetic的概念
AccordingtotheJVMSpec:"AclassmemberthatdoesnotappearinthesourcecodemustbemarkedusingaSyntheticattribute."Also,"TheSyntheticattributewasintroducedinJDKrelease1.1tosupportnestedclassesandinterfaces."
Iknowthatnestedclassesaresometimesimplementedusingsyntheticfieldsandsyntheticcontructors,e.g.aninnerclassmayuseasyntheticfieldtosaveareferencetoitsouterclassinstance,anditmaygenerateasyntheticcontructortosetthatfieldcorrectly.I'mnotsureifitJavastillusessyntheticconstructorsormethodsforthis,butI'mprettysureIdidseethemusedinthepast.Idon'tknowwhytheymightneedsyntheticclasseshere.Ontheotherhand,somethinglikeRMIorjava.lang.reflect.Proxyshouldprobablycreatesyntheticclasses,sincethoseclassesdon'tactuallyappearinsourcecode.IjustranatestwhereProxydidnotcreateasyntheticinstance,butIbelievethat'sprobablyabug.
Hmm,wediscussedthissometimeagobackhere.ItseemslikeSunisjustignoringthissyntheticattribute,forclassesatleast,andweshouldtoo.
注意上文的第一处黑体部分,一个类的复合属性表示他支持嵌套的类或者接口。
注意上文的第二处黑体部分,说明符合这个概念就是OO思想中的类的复合,也就是只要含有其它类的引用即为复合。
以上就是本文关于Java编程中的synthetic关键字的全部内容,希望对大家能有所帮助。感谢大家对本站的支持。