开发者

How to prevent an interface from getting extended

In Java, Is there a way to prevent extending an interface.

Since final cannot be added to an interface , i was curious开发者_开发百科 to know whether there was a way if any, to prevent extending an Interface.


The problem here is a conceptual one. Interfaces are meant to be extended because they can't be used as-is.

What you could do is put the interface inside a package and give it default visibility. With that only classes inside that package can implement that interface.

But with that solution you also lose the possibility to use the interface outside that package, so it is no real solution.


There is no way to prevent extending an interface.

You could detect if someone has extended your interface at runtime using reflection.


This is very similar to a previously asked question -- final interface in java.

I gave two answers.

  1. Yes, through byte code engineering. The resulting interface can not be extended but has no practical value
  2. Yes, annotations are interfaces that cannot be extended by other interfaces.

In addition, you can put the interface inside a class, give it the private access modifier, and make sure no interface in that class file extends it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜