Destroy only class inheritance

I would like to depreciate only the extension of this class, and not all the methods and fields contained in the class using @Deprecated annotations.

That is, a warning will occur if you extend this class, but references to methods or fields will not cause a warning. There are already several classes that extend this class, and I want obsolescence warnings to target these clients β€” I cannot break them yet (but they can be recompiled β€” compatibility with ABI is not needed).

Is this possible in Java 1.6 (JDT compiler)?

+7
source share
5 answers

Two considerations

1) The class can already be extended, so do not mark it final or you may violate backward compatibility.

2) You do not want the class to be extended, so it should be marked final.

I think what you should do is extend the old class with a new class, mark the old class obsolete and declare the new class final. In the new class, you can add the @SuppressWarning tag to calm the stale message, after which you should get a clean compilation.

Code using the old class will receive a @Deprecated warning, but will still compile. Code using the new class will compile cleanly. It’s a kind of β€œstrong offer” for your users instead of a backward compatible break and is quite easy to fix for them, since the API is 100% compatible.

+5
source

I doubt this is possible with the @Deprecated annotation.

If you have control over the sources, you can do the following:

  • Rename the current SomeClass to SomeClassSuper
  • Create a new class called SomeClass and continue with the extension of SomeClassSuper .
  • Make SomeClass final (which prevents clients from expanding it).

That is, go from

 class SomeClass { // ... } class SubClass extends SomeClass { // ... } 

to

 class SomeClassSuper { // ... } class SubClass extends SomeClassSuper { // ... } final class SomeClass extends SomeClassSuper { // ... } 
+4
source

No no. You can make the class final , but you violate existing extensions.

Perhaps this is possible thanks to the development of a custom processor for APT. But this will not apply in the general case.

+1
source

If this suits your design, perhaps you can make the necessary functionality (for example, constructors that descendants should have access to), and provide a protected + legacy constructor that extensions should use.

+1
source

The @Deprecated annotation does not support this, you must mark your final class. Although this leads to a compiler error, it is more logical to either extend your class safely, or it is an error for this.

0
source

All Articles