所以我有一个抽象类,并且我愿意将子类中的所有值存储在 ImmutableList 中。这是一个说明我的意思的例子
public abstract class Test {
...
public abstract int getValue();
}
然后是子类
public final class Example extends Test {
@Override
public int getValue() {
return 5;
}
}
有没有办法在启动时将 Test#getValue() 存储在 ImmutableList 中?
我尝试做类似的事情
public abstract class Test {
public static final ImmutableList<Integer> VALUES = ImmutableList.of();
public Test() {
VALUES.add(getValue());
}
public abstract int getValue();
}
然后打印出 VALUES 列表中的值。
public static void main(String[] args) {
Test.LIST.forEach(System.out::println);
}
但是没有成功。
最佳答案
使用 initializer block 。可以创建一个静态 block ,该 block 将在类加载时执行:
package foo.bar.baz;
import java.util.*;
public class Test {
static {
int MY_INT = 5;
List<Object> mylist = new ArrayList<Object>();
mylist.add(new Integer(MY_INT));
}
public Test() {
// ...
}
}
关于java - 在启动时存储抽象 int 的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34403926/