Search code examples
javaannotations

Java Function Annotation Help, use @Deprecated?


Scenario:
Java 1.6

class Animal { 
    private String name; 
    ...  
    public String getName() { return name; }  
    ...
}

class CatDog extends Animal {
    private String dogName;
    private String catName;
    ...
    public String getDogName() { return dogName; }
    public String getCatName() { return catName; }
    public String[] getNames() { return new String[]{ catName, dogName }; }
    ...
    public String getName() { return "ERROR! DO NOT USE ME"; }
}

Problem:
getName doesn't make sense and shouldn't be used in this example. I'm reading about @Deprecated annotation. Is there a more appropriate annotation method?

Questions:
A) Is it possible to force an error when this function is used (before runtime)?
B) Is there a way to display a customized warning/error message for the annotation method I will use? Ideally when the user is hovering over deprecated/error function.


Solution

  • Generally, you use @Deprecated for methods that have been made obsolete by a newer version of your software, but which you're keeping around for API compatibility with code that depends on the old version. I'm not sure if it's exactly the best tag to use in this scenario, because getName is still being actively used by other subclasses of Animal, but it will certainly alert users of the CatDog class that they shouldn't call that method.

    If you want to cause an error at compile time when that function is used, you can change your compiler options to consider use of @Deprecated methods to be an error instead of a warning. Of course, you can't guarantee that everyone who uses your library will set this option, and there's no way I know of to force a compile error just based on the language specification. Removing the method from CatDog will still allow clients to call it, since the client will just be invoking the default implementation from the superclass Animal (which presumably you still want to include that method).

    It is certainly possible, however, to display a custom message when the user hovers over the deprecated method. The Javadoc @deprecated tag allows you to specify an explanation of why a method was deprecated, and it will pop up instead of the usual description of the method when the user hovers over the method in an IDE like Eclipse. It would look like this:

    /**
     * 
     * @deprecated Do not use this method!
     */
     @Deprecated
     public String getName() {
         throw new UnsupportedOperationException();
     }
    

    (Note that you can make your implementation of the method throw an exception to guarantee that if the user didn't notice the @Deprecated tag at compile time, they'll definitely notice it at runtime).