Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can @SuppressWarnings("deprecation") apply to the use of a deprecated interface without applying to the whole class?

I have some legacy code that implements a deprecated interface. This particular component will soon be deprecated and removed itself so it does not make sense to refactor to address the root cause of the compiler warning. Instead I'd like to suppress it. However, I do NOT want the scope of the suppression to be for the entire class.

The code was originally:

public class Foo 
  extends 
    Bar 
  implements 
    DeprecatedBaz, 
    Qux { ... }

DeprecatedBaz is an interface which has been marked as @Deprecated and is a third party framework meaning I am unable to remove the @Deprecated. I'd like to suppress the warning but not deprecations for the whole class. Essentially I'd like to write:

public class Foo
  extends 
    Bar 
  implements
    @SuppressWarnings("deprecation") 
    DeprecatedBaz, 
    Qux { ... }

However this is invalid syntax and does not parse. So next I had hoped I might be able to do it at the import but this SO post seems to imply it must be done at a class level.

Alternatively I thought potentially applying it to all of the methods that interface dictates must be implemented might address the issue but that did not work either.

So it seems I'm forced to apply the annotation at the class level:

@SuppressWarnings("deprecation")
public class Foo
  extends 
    Bar 
  implements 
    DeprecatedBaz, 
    Qux { ... }

I don't like this because if someone edits this class and introduces new code which refers to deprecated code the warning will be swallowed.

Is there a way to limit the scope in this case?

like image 916
cclark Avatar asked Nov 11 '22 07:11

cclark


1 Answers

The @SuppressWarnings annotation can only be used at the point of a declaration. Even with the Java 8 annotation enhancements that allow annotations to occur in other syntactic locations, the @SuppressWarnings annotation can't be used where you need it in this case, that is, at the point where a deprecated interface occurs in the implements clause.

You're right to want to avoid putting @SuppressWarnings on the class declaration, since that will suppress possibly unrelated warnings throughout the entire class.

One possibility for dealing with this is to create an intermediate interface that extends the deprecated one, and suppress the warnings on it. Then, change the uses of the deprecated interface to the sub-interface:

@SuppressWarnings("deprecation")
interface SubBaz extends DeprecatedBaz { }

public class Foo ... implements SubBaz ...

This works to avoid the warnings because class annotations (in this case, @Deprecated) are not inherited.

like image 195
Stuart Marks Avatar answered Nov 14 '22 23:11

Stuart Marks