Reputation: 89
My problem statement is at below:
I am creating a library in java, for certain classes I would like the users should be able to extend my class but only at one level, those subclasses should not be available for sub-classing. It can be achieve if programmer their subclasses as final, but the decision would go to them. I want to control this from my library. how can I do this ?
Any help would be appreciated
Upvotes: 0
Views: 1645
Reputation: 10891
This is simple. Just write up license terms.
If your software is useful, then your requirement is unusual but not a deal breaker. For example, I would rather accept your requirement than spend money.
If your software is useless, then your requirement is unusual but not a deal breaker. No one would care.
Upvotes: -1
Reputation: 5389
You could use the Java reflection API and call getModifiers() to check and see if the class is final.
You might be able do this from your superclasses constructor. If not, you'll have to pick some method that's required to be called. If you detect that it's not final, you can throw an exception, exit the JVM, or whatever else you want to do to keep it from working.
I can't imagine a good reason to do this, however. As a user of your library I would be annoyed by this arbitrary restriction.
Also, a user of your library could always wrap your object in their own object, and extend it by composition instead of inheritance.
Upvotes: 3
Reputation: 44808
I suppose you could implement something like this with reflection:
public abstract class ExtendOnce {
public static class Subclass extends ExtendOnce {
}
public static class SubSubclass extends Subclass {
}
protected ExtendOnce() {
if (!getClass().getSuperclass().equals(ExtendOnce.class)) {
throw new RuntimeException(
"You extended this class more than once!");
}
}
public static void main(String[] args) {
System.out.println(new Subclass());
System.out.println(new SubSubclass()); // throws exception
}
}
However, the more important question you need to be asking yourself is do you actually need this restriction?
Upvotes: 11