方法内部的匿名内部类
请看下面的代码:
import java.util.ArrayList;
import java.util.List;
class Main{
public static <T> List<T> modifiedList(final List<T> list){
return new ArrayList<T>(){
@Override
public boolean add(T element){
super.add(element);
return list.add(element);
}
};
}
public static void main(String[] args) {
List<String> originalList=new ArrayList<String>();
List<String> duplicateList=modifiedList(originalList);
originalList.add("1");
originalList.add("2");
originalList.add("3");
System.out.println(originalList+" "+duplicateList);
duplicateList.add("4");
duplicateList.add("5");
duplicateList.add("6");
System.out.println(originalList+" "+duplicateList);
}
在上面的代码中,在方法modifiedList()中声明的匿名内部类的实例能够访问传递给该方法的参数。 AFAIK Java 为内部类创建一个单独的字节码文件。
谁能解释一下 Java 在字节码级别如何处理这些局部变量绑定?我的意思是,Java 究竟如何跟踪作为参数传递给该方法的对象的引用?
任何帮助将不胜感激!
[抱歉我的英语不好!如果您理解我的问题,请编辑这篇文章并删除语法错误。谢谢!]
Please have a look at following code :
import java.util.ArrayList;
import java.util.List;
class Main{
public static <T> List<T> modifiedList(final List<T> list){
return new ArrayList<T>(){
@Override
public boolean add(T element){
super.add(element);
return list.add(element);
}
};
}
public static void main(String[] args) {
List<String> originalList=new ArrayList<String>();
List<String> duplicateList=modifiedList(originalList);
originalList.add("1");
originalList.add("2");
originalList.add("3");
System.out.println(originalList+" "+duplicateList);
duplicateList.add("4");
duplicateList.add("5");
duplicateList.add("6");
System.out.println(originalList+" "+duplicateList);
}
In the above code, the instance of an anonymous inner class declared in the method modifiedList() is able to access the parameter passed to that method. AFAIK Java creates a separate bytecode file for inner classes.
Can anyone explain how these local variable bindings are handled by Java at the bytecode level? I mean, how exactly does Java keep track of the reference to the object passed as a parameter to that method?
Any help would be greatly appreciated!
[Sorry for my poor English! If you understand my question, please edit this post and remove the grammatical errors. Thanks!]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
本质上,代码是由编译器重写为(注意我没有尝试编译它......,可能有错误):
和
Essentially the code is rewritten by the complier as (note I didn't try to compile it..., might have errors):
and
Java允许这种奇怪的事情只是为了让程序员的事情变得更容易。
这两个代码在语义上是相同的,并且归结为相同的字节码。
Java allows such a strange thing just in order to make things easier for programmers.
Both the codes are semantically same and boil down to the identical bytecode.