My own deprecated annotation - java

It's possible to create an annotation like #deprecated, I mean, with deprecated code-style?
I'd like to create an annotation to indicates that some messages were removed from the communication protocol, so I'd not want to use the deprecated annotation because I want 1) give a better and more suggestive name for my annotation, like "message removed" 2) give parameters for my annotation, e.g. (protocol = 5) -removed since protocol 5.
But, I want to keep this strikethrough code for others know that this message has been removed just by looking to the code.

#Deprecated annotation is designed for the development environment (generally but not only). It does nothing itself. But for IDE it is the some kind of marker and when it "see" that annotation - it performs some logic (for example "strikethrough" the code). The goal of my post is to tell that it is not enough to develop and use the annotation : it must me supported by environment.

There are two things you can do:
Add the
#Deprecated annotation to the method, and
Add a
#deprecated tag to the javadoc of the method
You should do both!
Quoting the java documentation on this subject:
Starting with J2SE 5.0, you deprecate a class, method, or field by using the #Deprecated annotation. Additionally, you can use the #deprecated Javadoc tag tell developers what to use instead.
Using the annotation causes the Java compiler to generate warnings when the deprecated class, method, or field is used. The compiler suppresses deprecation warnings if a deprecated compilation unit uses a deprecated class, method, or field. This enables you to build legacy APIs without generating warnings.
You are strongly recommended to use the Javadoc #deprecated tag with appropriate comments explaining how to use the new API. This ensures developers will have a workable migration path from the old API to the new API

When looking at the source code of the Deprecated annotation, you will see that there is nothing specific that makes it appear with the strikethrough. It is a feature of the IDE to mark #Deprecated code with a strikethrough.
Here it is:
#Documented
#Retention(RetentionPolicy.RUNTIME)
public #interface Deprecated {
}

+1 for oleg.lukyrych's answer BUT you can still do something.
Create your annotation (with all the parameters you want), then add a static code analysis to your build procedure. i.e. PMD with a custom rule. PMD is well know and well integrated in various IDE and continuous build environment like hudson/jenkins. The analysis will produce you a nice report of the (mis)use of your deprecated message.
It is not as nice as having it into your editor but it make the job.
Hope this helps.

Mayur Gupta,
I created a annotation MessageRemoved:
public #interface MessageRemoved {
Protocol protocol();
}
And a Enum:
public enum Protocol {
P01, P02, P03, P04, P05
}
Using a Annotation:
#MessageRemoved(protocol = Protocol.P05)
public class OldMessage extends Message{
}
This facilitates the traceability of messages removed. Using only annotation #Deprecated this is not possible.

Related

Alternatives to #Deprecated SerializationFeature.WRITE_EMPTY_JSON_ARRAYS

I'm having difficulties figuring out the correct way to fix the deprecation warnings on SerializationFeature.WRITE_EMPTY_JSON_ARRAYS.
Javadocs state that
Since 2.8 there are better mechanism for specifying filtering;
specifically using com.fasterxml.jackson.annotation.JsonFormat or
configuration overrides.
but I would assume that
ObjectMapper.configure(SerializationFeature.WRITE_EMPTY_JSON_ARRAYS, false);
is a configuration override, although the line above triggers a deprecation warning.
What are other alternatives that do not pollute model classes with yet another annotation? I want to configure the behaviour globally.
At the class level, you can use the #JsonInclude like:
#JsonInclude( JsonInclude.Include.NON_EMPTY )
public class MyClass ...
Also, at the mapper level you can do something like:
mapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
The Javadoc is just plain wrong.
"using com.fasterxml.jackson.annotation.JsonFormat": There are plenty of cases where annotations are patently NOT better, most notably when you can't annotate the POJOS because you don't own them, or when you need to override the annototations to get a different behavior than you usually want.
"configuration overrides": That would be great, but to my knowledge there are no other overrides that will take precedence over annotations.
From the user perspective, the only thing bad about the deprecated option is that it is deprecated, and thus might not be supported in the future. That is of course a real concern - you might one day have to choose between a vital security update and keeping your code working without a rewrite.

How can I include #Annotations in JavaDoc? [duplicate]

This question already has an answer here:
Is there a way to get the javadoc tool to document annotations?
(1 answer)
Closed 4 years ago.
I would like to document some properties of classes and methods in JavaDoc and be able to load these information at runtime. Therefore I thought it might be convenient to write a custom annotation and annotate all necessary files and methods with this annotation. With this annotation, I could load these information at runtime.
Here's a hypothetic code snippet to demonstrate my use case:
public class ImportantClass {
#DetailedDescription(description="originated from data source XYZ")
public void importantMethod() {
// snip
}
}
The String "originated from data source XYZ" should be displayed in the JavaDoc and be readable via reflections or something similar. My problem is that the JavaDoc does not contain annotation information.
Is it possible to configure the JavaDoc task (preferrably with Maven) to include annotation information?
Clarification: I'm not interested in doclets (~javadoc annotations) as they are not readable at runtime.
I finally found a nice solution without duplication. Use the #Documented annotation on the annotation interface (DetailedDescription in this case) and all instances of this annotation are documented in the JavaDoc.
See this question:
Is there a way to get the javadoc tool to document annotations?
This is more of a comment than an answer, but it is long so I need this format
Why do you want an annotation for that? The Oracle documentation says that for this kind of use, you should use both a javadoc tag and an annotation. From the link I provided:
If you need to affect both program semantics and documentation, you probably need both an annotation and a tag. For example, our guidelines now recommend using the #Deprecated annotation for alerting the compiler warning and the #deprecated tag for the comment text
Use javadocs, it provides exactly what you are trying to achieve.
Annotations provide metadata at the code level, and are meant to play role in the behaviour of your app. Should not be used for documentation.

How do we call `#something` before methods in Java?

As I was trying to sharpen my Java skills by creating a Minecraft server plugin, I came across a #EventHandler in a code example for Bukkit plugin development. This is was put just over a method implementation and I was wondering what it is called.
I remember having seen some #Override somewhere else and I want to learn what it is called so I can search it online...
it is Annotation.
Annotations, a form of metadata, provide data about a program that is not part of the program itself. Annotations have no direct effect on the operation of the code they annotate.
From the doc the usage of annotations are mainly
Information for the compiler — Annotations can be used by the compiler to detect errors or suppress warnings.
Compile-time and deployment-time processing — Software tools can process annotation information to generate code, XML files, and
so forth.
Runtime processing — Some annotations are available to be examined at runtime.
This thing is called an annotation. In Python the counterpart of Java annotations are called decorators.
OK, I will not replicate the link to what an annotation is. Rather, I will talk about how they can operate.
Annotations have both a Target and a Retention; optionally, they can also be #Documented so that you know this annotation has been present at some time in your source code. Now, onto the target and retention since these two "meta-annotations" will definitely have an influence on what you can expect:
the target determines what that annotation can be applied to; this can be a whole class, an instance variable, a method, a... Well, see the doc.
the retention determines how "long" this annotation persists in your source code. The two retention policies used in majority are SOURCE and RUNTIME.
In an annotation such as yours, it is typically an annotation with a runtime retention policy. Such an annotation can be used, at runtime, by specific processing code, to change the behaviour of the target so that its behaviour be controlled by this processing code. Such code is logically called an annotation processor.
Annotations have begun to take quite some an importance in some JSRs:
JSR 330 defines #Inject, #Provider etc as runtime annotations, so that frameworks willing to do dependency injection can rely on these annotations being present; this is the case, for instance, for dependency injection frameworks such as Dagger and Guice (since version 3.0);
JSR 305 defines #Immutable, #ThreadSafe, #NotThreadSafe, #Nullable, #Nonnull with a source retention policy, and #Documented; these annotations can be used by static code analysis tools, and of equal importance, they are typically #Documented as well. Therefore you know what to expect of them.
It is just a annotation.
#Override for ie is used in methods that is overriding method with the same name in the extended "super class"
It's an annotation.
While it usually has no direct effect on code, some object databases may use it to specify the behavior of one or more fields in regard to indexing, keying, or other functions.

Should I use JavaDoc deprecation or the annotation in Java?

There are at the moment, two ways to mark code as depreacted in java.
Via JavaDoc
/**
* #deprecated
*/
Or as an annotation:
#Deprecated
This is my problem - I find it a bit too much to declare both, when marking a method as deprecated when using Eclipse. I really just want to use one of them.
However does using the annotation give the compiler actual useful additional information?
But only using the annotation, I cannot state why the method is deprecated - I can only do that with JavaDoc, and deprecating a method without specying why is bad.
So, can I only use one of them? Or should I really just learn to specify both?
You should use both. The Annotation allows the compiler to display a warning whenever a deprecated method is used, and the javadoc explains why. Both are important.
As per Oracle's Java Annotations tutorial:
When an element is deprecated, it should also be documented using the Javadoc #deprecated tag...
From the horse's mouth:
NOTE: The Java Language Specification
requires compilers to issue warnings
when classes, methods, or fields
marked with the #Deprecated annotation
are used. Compilers are not required
by the Java Language Specification to
issue warnings when classes, methods,
or fields marked with the #deprecated
Javadoc tag are accessed, although the
Sun compilers currently do so.
So basically, if you want a guarantee that there will be compiler warnings, you need to use the annotation. And because of some API designer's breathtaking incompetence, you need to specify the javadoc tag as well to give an explanation.
Personally, I'd say the annotation is useless and should be omitted until it's fixed, since any good compiler or IDE will display warnings with the javadoc tag as well.
You should write both.
The #Deprecated Anotation is for the Compiler and the #deprecated JavaDoc tag is for the Person who wants to know why this is deprecated.
An example can look like this:
/**
* #deprecated We dont need this Method because ...
*/
#Deprecated
public void doStuff(){..}
You should specify both.
The annotation lets the compiler know about it and trigger warnings when the method is used.
The JavaDoc attribute lets developers know about before they start using it.
These are two very different things!
This can be easily dealt with a good IDE.
Eclipse Neon, for eg. automatically adds #Deprecated annotation, when I create a javadoc #deprecated on a method or field.
So I simply write the javadoc with the appropriate explanation and let the IDE take care of adding the #Deprecated annotation, the minute I save the file.

Useful Java Annotations

I'm interested in finding out exactly which Java annotations people think are most useful during development. This doesn't necessarily have to limited to the core Java API, you may include annotations you found in third party libraries or annotations you've developed yourself (make sure you include a link to the source).
I'm really interested in common development tasks rather than knowing why the #ManyToOne(optional=false) in JPA is awesome...
Include the annotation and a description of why it's useful for general development.
I doled out a bunch of upvotes for other users, but just to give my two cents the only three annotations I use with any regularity in development are the main annotations used directly by the compiler:
#Override - Great for making it explicit in your code when you're overriding another method. Also has the extra benefit of being flagged as a compilation error if you don't override a method the way you think you are (see this other SO post). This flag informs the compiler that you're intending to override something, so if you don't (e.g. you forget an argument in the method signature), the compiler will catch it.
#Deprecated - Indicate whatever you're marking as something that should not be used from this point forward. The compiler will generate warnings for use of any code elements you've marked as deprecated. In general, deprecation says "this was in here in the past, but it may go away in a future version." Make sure you also use the associated "#deprecated" Javadoc flag in conjunction with this too to tell people what they should use instead.
#SuppressWarnings - Tell the compiler to suppress specific warnings it would otherwise generate. This can be useful for things like when you intentionally want to use deprecated methods, you can block out the deprecation warning. I tend to use it a lot to block out everyone's favorite "Serialization UID" warning on serializable classes (whether or not you should do that is another debate for another time). Just handy for those cases where you know something you're doing is generating a warning, but you're 100% sure it's the proper behavior you want.
Look at the Sun Annotations Guide and check out the section "Annotations Used by the Compiler". These three are given a fairly lengthy discussion.
The Java Concurrency in Practice annotations
Very useful for describing exactly how your code is or isn't thread safe...
I find the he concurrency-related annotations defined by Brian Goetz in his book "Java Concurrency In Practice" to be very useful:
#GuardedBy
#Immutable
#NotThreadSafe
#ThreadSafe
They're particularly useful as FindBugs has patterns that use them.
A jar and documentation is freely available at http://www.javaconcurrencyinpractice.com/
#Override has my vote. It makes it instantly clear what your method is about and makes your code more readable.
#Test
(JUnit 4) It's made writing and understanding test files quite a bit cleaner. Plus, the ability to add the expected attribute has saved a few lines of code here and there.
#Deprecated
Introduced in Java 5.
It helps developers see what's deprecated in IDEs. (Prior to this, most IDEs could still pull a #deprecated out of the javadoc comments for a particular method, but this annotation was a nice way to make it meta-information about the method itself, rather than a comment in documentation.)
It's also used by the compiler to print out warnings when you're using deprecated methods.
Personally I've been looking at the JSR303 Bean Validation and the annotations it provides, I imagine these will become more commonplace, there's only a few implementations of the JSR so far, but they provide annotations such as:
#NotNull private String name;
#NotNull #Size(min = 5, max = 30) private String address;
More info here: http://jcp.org/en/jsr/detail?id=303
these should be useful, you can define them in your projects to better communicate intentions:
#ThreadSafe
#Immutable
#ValueObject
#BagOfFunctions (e.g. java.util.Collections)
etc
Here are some Annotations I use in day to day development
Spring:
#Autowired - used to Auto wire beans
#Rollback - If set to true it will rollback all DB operations done inside the test case
JUnit:
#Test - Tell that a method is a test case
#Ignore - If you want to ignore any of the test cases
#Before - Code that should run before each test case
JPA:
#Entity - To tell that a POJO is a JPA Entity
#Column - Map the property to DB column
#Id - tell that a java property is Primary key
#EmbeddedId - Used for Composite Primary Keys
#Transient - This property should not be persisted
#Version - Used to manage optimistic locking
#NamedQuery - Used to declare Native SQLs
#OneToMany - One to Many relationship
#ManyToOne - Many to one Relationship
I have included only the most essential ones.You can find details about all the JPA annotations from the following links.
http://www.oracle.com/technology/products/ias/toplink/jpa/resources/toplink-jpa-annotations.html
http://www.hiberbook.com/
We started using a compile time tool called lombok (http://projectlombok.org/). You annotate classes, members, etc. and methods are automatically generated at compile time. It's a great productivity boost and saves hundreds of lines of tedious coding.
Do you want a toString() method to be automatically generated? Just annotate your class with #ToString.
Tired of having to define getters and setters for your members? Annotate your class with #Getter and / or #Setter and they're automatically added.
Want to have an SLF4J logger to log stuff? #Slf4j creates a private static final logger for you.
#Data
public class MyBean {
// Getters for x and y, setter for y and constructor with x as arg automatically created!
// toString() and hashCode() methods are there too!
private final int x;
private int y;
}
.
#Slf4j
public class SomeClass {
public void doSomething() {
log.info("I've got log.");
}
}
Setting it up is very easy: just add a provided maven dependency. There's also a tiny Eclipse / IntelliJ plugin.
Check out the full list of features there: http://projectlombok.org/features/index.html
Junit 4 provides very useful annotations. Here's a tutorial illustrating the usage of annotations to define tests.
e.g.
#Test(expected= IndexOutOfBoundsException.class) public void empty() {
new ArrayList<Object>().get(0);
}
As Dan pointed out below, TestNG did this originally.
#Given
allows one JUnit test to build upon the return value of another test. Requires JExample.
#FunctionalInterface
Useful to communicate that a particular interface is meant to be functional. If the single abstract method is removed, it'll throw a compilation error.
I started a weekend project to implement a Programming By Contract framework using method and parameter annotations e.g.
//...
myMethod (#NotNull String a, #NotNullOrEmpty String b){
if ( !validate() ){
//raiseException
}
}
I got stuck at the point of getting param values automatically. Java reflection does not have it. never understood several people's ranting on Java till I came across this limitation.

Categories