Kew*_*ang 13 java parameters final adapter anonymous-class
我有以下静态工厂方法,从int数组创建列表视图:
public static List<Integer> newInstance(final int[] numbers) {
return new AbstractList<Integer>() {
@Override
public Integer get(int index) {
return numbers[index];
}
@Override
public int size() {
return numbers.length;
}
};
}
public static void main(String[] args) {
int[] sequence = {10, 20, 30};
List<Integer> list = ListFactory.newInstance(sequence);
System.out.println("List is "+list);
}
Run Code Online (Sandbox Code Playgroud)
在"Effective Java"中,Joshua Bloch提到了这一点
作为适配器,允许将int数组视为Integer实例列表.
但是,我记得Adapter使用组合,匿名列表实现的实例应该使用int []作为成员字段.
如果int []输入参数不是匿名列表实现的成员字段,那么它究竟存储在哪里?
如果有人能提供一些见解或一些链接来寻找更多信息,我将不胜感激.
您可以使用它javac -d . -XD-printflat ListFactory.java来查看编译器如何理解内部类.实际上,您的示例中有两个Java类.该ListFactory(注意如何numbers被传递到的构造函数ListFactory$1):
public class ListFactory {
public ListFactory() {
super();
}
public static List newInstance(final int[] numbers) {
return new ListFactory$1(numbers);
}
}
Run Code Online (Sandbox Code Playgroud)
以及匿名实施的代表AbstractList:
class ListFactory$1 extends AbstractList {
/*synthetic*/ final int[] val$numbers;
ListFactory$1(/*synthetic*/ final int[] val$numbers) {
this.val$numbers = val$numbers;
super();
}
@Override()
public Integer get(int index) {
return Integer.valueOf(val$numbers[index]);
}
@Override()
public int size() {
return val$numbers.length;
}
@Override()
/*synthetic*/ public Object get(/*synthetic*/ int index) {
return this.get(index);
}
}
Run Code Online (Sandbox Code Playgroud)
标记为合成的方法和字段由编译器生成,作为程序员无法访问,但在运行时用于访问int数组.确实有一个val$numbers字段包含对int数组的最终引用.
顺便说一句,你还可以看到拳击int到Integer的Integer get(int index)和符合生(非通用)List接口,一个额外Object get(int index)的生成方法委托类型安全的Integer get(int index)实现.
| 归档时间: |
|
| 查看次数: |
209 次 |
| 最近记录: |