Java中的synthetic详解

本文详细介绍了Java中synthetic标记的含义及其应用,包括内部类如何通过synthetic字段访问外部类的方法和私有属性,以及assert关键字生成的synthetic静态字段。此外,还探讨了synthetic在嵌套类和接口支持中的作用,揭示了Java编译器在源代码转换过程中的机制。
摘要由CSDN通过智能技术生成

https://blog.csdn.net/moakun/article/details/80577702

synthetic介绍

有synthetic标记的field和method是class内部使用的,是编译器自动生成的,正常的源代码里不会出现synthetic field。

举例

1.内部类访问外部类方法

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

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

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

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

所有父对象的非私有成员都通过 this$0来访问。

2.assert 关键字

还有许多用到synthetic的地方。比如使用了assert 关键字的class会有一个
synthetic static boolean $assertionsDisabled 字段。使用了assert的地方 :

assert condition;

在class里被编译成

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

3.内部类访问外部类私有属性

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

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思想中的类的复合,也就是只要含有其它类的引用即为复合。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值