加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

浅谈Java编程中的synthetic关键字

发布时间:2020-12-14 14:12:10 所属栏目:Java 来源:网络整理
导读:java synthetic关键字。有synthetic标记的field和method是class内部使用的,正常的源代码里不会出现synthetic field。小颖编译工具用的就是jad.所有反编译工具都不能保证完全正确地反编译class。所以你不能要求太多。 下面我给大家介绍一下synthetic 下面的

java synthetic关键字。有synthetic标记的field和method是class内部使用的,正常的源代码里不会出现synthetic field。小颖编译工具用的就是jad.所有反编译工具都不能保证完全正确地反编译class。所以你不能要求太多。

下面我给大家介绍一下synthetic

下面的例子是最常见的synthetic field

Java代码

class parent {
		public void foo() {
		}
		class inner {
			inner() {
				foo();
			}
		}
	}

非static的inner class里面都会有一个this$0的字段保存它的父对象。编译后的inner class 就像下面这样:
Java代码

class parent$inner{
	synthetic parent this$0;
	parent$inner(parent this$0)
	{
		this.this$0 = this$0;
		this$0.foo();
	}
}

所有父对象的非私有成员都通过 this$0来访问。
还有许多用到synthetic的地方。比如使用了assert 关键字的class会有一个synthetic static boolean $assertionsDisabled 字段
使用了assert的地方

assert condition;
在class里被编译成
Java代码

if(!$assertionsDisabled && !condition){
	throw new AssertionError();
	}

还有,在jvm里,所有class的私有成员都不允许在其他类里访问,包括它的inner class。在java语言里inner class是可以访问父类的私有成员的。在class里是用如下的方法实现的:

Java代码

class parent{
		private int value = 0;
		synthetic static int access$000(parent obj)
		{
			return value;
		}
	}

在inner class里通过access$000来访问value字段。
synthetic的概念

According to the JVM Spec: "A class member that does not appear in the source code must be marked using a Synthetic attribute." Also,"The Synthetic attribute was introduced in JDK release 1.1 to support nested classes and interfaces."

I know that nested classes are sometimes implemented using synthetic fields and synthetic contructors,e.g. an inner class may use a synthetic field to save a reference to its outer class instance,and it may generate a synthetic contructor to set that field correctly. I'm not sure if it Java still uses synthetic constructors or methods for this,but I'm pretty sure I did see them used in the past. I don't know why they might need synthetic classes here. On the other hand,something like RMI or java.lang.reflect.Proxy should probably create synthetic classes,since those classes don't actually appear in source code. I just ran a test where Proxy did not create a synthetic instance,but I believe that's probably a bug.

Hmm,we discussed this some time ago back here. It seems like Sun is just ignoring this synthetic attribute,for classes at least,and we should too.

注意上文的第一处黑体部分,一个类的复合属性表示他支持嵌套的类或者接口。

注意上文的第二处黑体部分,说明符合这个概念就是OO思想中的类的复合,也就是只要含有其它类的引用即为复合。

总结

以上就是本文关于Java编程中的synthetic关键字的全部内容,希望对大家能有所帮助。感谢大家对本站的支持。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读