I want to know if it is possible to create an Annotation
that enforces a specific Return Type?
What I would like is a way to create an Annotation
and use it like:
@MarkerAnnotationForcingStringReturnType
public String someWebflowMethod(...){
...
return "someString";
}
Then I can have any metho开发者_JAVA百科d name I want, but it will have to return, a String
, for example.
Doesn't the method signature itself enforce a specific return type?
You could create your own annotation and then write your own annotation processor which could enforce it.
I don't know of one built in... and frankly I'm not sure I see the point. If you're going to be vigilant enough to write the annotation, why would you not be vigilant enough to get the method return type right? Under what circumstances would you get the annotation right but the method wrong?
By themselves, annotations are simply metadata - that is, "comments" that are attached to bits of code and are included in the bytecode itself (possibly).
You could write a processor using apt that would validate this at compile-time if you really wanted to.
But I find that declaring a method to return String
is just as robust and more easily understandable by a typical Java developer. Do you really have a good reason for doing this? If you're worried that someone might change the return type, they might just as easily delete your annotation. If you want to prevent someone from making these changes, a comment is arguably more effective than an annotation that they might remove for "being superfluous" (hey, we're talking about developers that you're expecting to invalidate base requirements here through incompetence/lack of awareness...).
精彩评论