In java I need to prevent Level1 class (look at following sample code) from being derived for more than two levels. Deriving till Level2 and Level3 is fine but if class is derived by Level4 then exception should be thrown. Look at following code sample.
Code sample:
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() {
}
}
From above code sample I am not proposing solution using static int level counter. I am just trying to explain the issue.
Is it possible in Java by implementing some logic or by using some API where Level1 base class can count number of levels it has been derived?
introspection api can help you handle that, try something like :
by the way, why do you want to do that ?