在java中,我需要防止Level1类(请看下面的示例代码)从两个以上的级别派生.导出到Level2和Level3很好,但是如果class是由Level4派生的,那么应该抛出异常.请看下面的代码示例.
代码示例:
class Level1 {
private int level = 1;
protected Level1() throws RuntimeException {
level++;
//System.out.println(level);
if (level > 2) {
throw new RuntimeException("Can't implement more than 2 levels");
}
}
}
class Level2 extends Level1 {
protected Level2() {
}
}
class Level3 extends Level2 {
Level3() {
}
}
class Level4 extends Level3 {
Level4() {
}
}
Run Code Online (Sandbox Code Playgroud)
从上面的代码示例我不建议使用静态int级计数器.我只想解释这个问题.
是否有可能在Java中通过实现某些逻辑或使用某些API,其中Level1基类可以计算它已导出的级别数?
您可以在构造函数中使用反射并遍历this.getClass()的继承链以查看嵌套级别.实际上对this.getClass().getSuperClass()== Level1.class的测试应该已经完成.
小智 5
内省api可以帮助您处理,尝试类似:
protected Level1() throws RuntimeException {
if (getClass().equals(Level1.class)) {
return;
}
if (getClass().getSuperclass().equals(Level1.class)) {
return; // first level or inheritance
}
if (getClass().getSuperclass().getSuperclass().equals(Level1.class)) {
return; // second level or inheritance
}
// else
throw new RuntimeException("Can't implement more than 2 levels");
}
Run Code Online (Sandbox Code Playgroud)
顺便问一下,你为什么要那样做?
| 归档时间: |
|
| 查看次数: |
627 次 |
| 最近记录: |