【发布时间】:2018-03-18 16:23:41
【问题描述】:
所以我又在玩java了,在这样做的时候,我遇到了一个有趣的问题。
我正在尝试为自己编写一个小的注册服务。如果某个类型的对象通过其构造函数进行实例化,它将从我的注册服务中检索一个 id 并添加到对象的服务列表中。
这是一个示例对象
public class Test {
private final Long id;
public Test() {
this.id = TestRegistration.register(this);
throw new IllegalAccessError();
}
public Long getId() {
return this.id;
}
}
这是一个示例服务
public class TestRegistration {
private final static Map<Long, Test> registration = new HashMap<>();
protected final static long register(final Test pTest) {
if (pTest.getId() != null) {
throw new IllegalStateException();
}
long freeId = 0;
while (registration.containsKey(freeId)) {
freeId = freeId + 1;
}
registration.put(freeId, pTest);
return freeId;
}
protected final static Test get(final long pId) {
return registration.get(pId);
}
}
现在你可以看到,我的类Test 的构造函数根本无法成功执行,因为它总是抛出一个IllegalAccessError。但是在抛出这个错误之前,我的TestRegistration 类的register(...) 方法在构造函数中被调用。在这个方法中,它被添加到注册Map。所以如果我会运行例如这段代码
public static void main(final String[] args) {
try {
final Test t = new Test();
} catch (final IllegalAccessError e) {
}
final Test t2 = TestRegistration.get(0);
System.out.println(t2);
}
我的TestRegistration 实际上包含在调用我的Test 类的构造函数时创建的对象,我可以(这里使用变量t2)访问它,即使它在第一次没有成功创建地点。
我的问题是,如果 Test 的构造函数在没有任何异常或其他中断的情况下成功执行,我能否以某种方式从我的 TestRegistration 类中检测到?
在你问我为什么首先抛出这个异常之前,这是我的答案。测试可能有我还不知道的潜在子类,但仍将在我的 TestRegistration 类中注册。但由于我对这些子类的结构没有影响,我无法判断它们的构造函数是否会抛出异常。
【问题讨论】:
标签: java constructor