I understand the purpose of class annotations, thanks to How and where are Annotations used in Java?. What is the purpose of package annotations, as described in this blog post and ยง7.4.1 of the Java Language Specification?
Why would you want to associate metadata with a package? What kinds of things could you do?
bnd tool (and maven-bundle-plugin) makes use of package annotations. Putting #Version and #Export annotation in package-info.java allows it to generate OSGi metadata.
javadoc uses package annotations.
JAXB uses package-level annotations, for example, to specify mapping of a Java type to XML Schema type package-wide. Package annotations are also used in JBoss's xml binding.
Struts 2 Convention plugin uses an annotation to specify a default interceptor for all actions in a package.
There are some package-level Hibernate Annotations. An example of those annotations' usage can be found here.
I suppose #Deprecated would make sense. And maybe something like #Generated if the whole package was generated by some tool from non-Java source. Or #Internal if this package is not part of a public API.
Maybe OSGi tools (where you need to declare the versions of your packages, and the packages you depend on) could make use of this, too.
Has anyone seen those in the wild?
Two reasons that I can think of:
Annotating special packages to let some aspects (for example using AspectJ) to weave the classes in them for specific functionality.
Annotating some packages that are to be read by some tools, for example for source, meta-data or other kinds of resource generation.
JAXB for example allows most annotations that are normally used on a type to be equally well applied to a package. The meaning in that case would be to specify the default for all classes in that package.
For example, if you want all properties of all classes in a package that are exposed via getter/setters to be mapped in XML you could specify #XmlAccessorType(XMLAccessType.PROPERTY) on each class or simply specify it on the package.
This is not the real purpose, but I'm using them as a workaround to avoid recompilation of the package-info.java files.
The problem is that javac (and the Ant task <javac>) creates no class file for the package-info.java if there is only documentation (the reason for their existence) and the package bla; statement, and that the ant task recompiles every file for which there is no (or an older) corresponding .class file.
Adding a dummy annotation there (like SuppressWarnings) had the effect that a package-info.class is produced and thus the file is not recompiled until changed again.
(Ant 1.8.0 solved this by creating an empty package-info.class, even if there was no annotation, but I'm using an older ant here.)
Test metadata -- that is metadata around test packages (unit tests or otherwise). You can ascribe various pieces of test metadata that are appropriate at the package level, such as: features, owners, versions, bugs/issues, etc. These could be refined at the class or method level, but having package-level definitions or defaults could be handy for brevity. I've utilized a variant of this approach (before the benefit of annotations).
A similar argument could be made for generalized code metadata around the same sorts of things: features, ownership, defects, historical information, etc.
Related
I am using the openapi-generator-maven-plugin to generate model sources.
Is there a way to generate them only with fields and without any access methods?
I want the access methods to be generated via lombok with the additionalModelTypeAnnotations configOption in the maven configuration of the openapi-generator-maven-plugin
You can implement those customizations by changing the Mustache templates
Fetch the templates of the Java framework (ie spring-boot) you want to use (ie openapi-generator-cli author template -g spring --additional-properties=library=spring-boot -o tmp/mytemplates
Modify the local model.mustache file to import the packages you want (lombok) and pojo.mustache to remove the getters/setters. There might other customisations necessary (each framework templates are different) but this the recommended approach.
As #beppe suggested in their answer, this can easily be done by modifying the mustache template. However, I highly advice against it. In doing so, you discard many of the the features included with the model objects created by the generator. Some of the features you lose are:
Bean Validation
Jackson Serialization Library Support
Support for vendor extensions
By adding the Lombok annotation to the generated files, you are basically ignoring the main point of the generator, which is to generate files that support each other. You are instead using a generator to call a generator.
Finally, the amount of customization necessary to make the lombok library work with the mustache files is much more than is really worth it. Sure, you can add #Data or #Jacksonized to your model, but what about #JsonIgnore? Do you want to use parameters in your Lombok calls? Because you can't set the builder classname via #Builder(builderClassName = "EmployeeBuilder"). That would be hardcoded. Instead, you'd have to use mustache parameters, such as #Builder(builderClassName = {{$builderClassName}}), which you'd then have to define elsewhere. What about #Builder vs #SuperBuilder? Which one do you use in which situation? How do you define and template it?
At this point, you might as well rewrite the entire pojo.mustache to be able to use the lombok annotations. But, what if you need the old pojo.mustache functionality elsewhere? Now you need to write a custom generator to determine which mustache to use in which situations.
It is best to just build the domain models as the openapi-generator intends and use them as they are. You can add annotations if you need to via vendor extensions such as x-field-extra-annotation and x-class-extra-annotation if you really feel the need to.
Is it possible to set the #ExtensionMethod for the whole project?
For example if I extend Object with a method isNull(), would it be possible to use that in the whole project with only define the #ExtensionMethod in for example a config class and use it everywhere without declaring it on each class?
Lombok contributor here:
No. The primary reason is 'surprises' - lombok would then be having an effect on a source file that has zero mentions of lombok, anywhere in side it (no types or imports; a CMD+F for lombok would produce zero results), and yet, doesn't compile without it.
Lombok does have a config system (lombok.config) and that would be the place to define some fully qualified class names to be treated as automatically considered sources of extension methods for all java source files in the directory where this config file appears and all subdirs of that directory. But, this feature doesn't exist right now, and won't, until I and other major contributors hold a bit of a debate on whether we want to open this can of worms.
Some meet-in-the-middle solution where there is a list of 'default extensions', but you still need to enable it by annotating the class with #DefaultExtensionMethods or what not (or just #ExtensionMethod and nothing more, with no arguments) might be where we draw the line. I'll keep it in mind.
I write own DI/IoC library on java. I want to take classes which have some annotation (e.g. my own annotaion) in given package to scan, like in Spring IoC. But reflection from jdk is not appropriate, because i can't traverse through package. I took decision to use SimpleFileVisitor to take classes, but i don't want to use this "crutch". How to take classes with specific annotation in given package?
You must use Reflection lib form google.
Is annotation processing still an active part of Java 6+, or is it something that has been deprecated/discouraged/obsolesced. If obsolesced, why (why is it no longer needed/useful)? And if it's still extremely useful and "active" (a new Java project developing against the Java 6+ JDK would still benefit from it), please confirm/correct my understanding of how annotation processors are used:
You create your own annotation class, say #MyAnnotation
You mark certain classes, methods, fields, etc. with #MyAnnotation
During the build process, you invoke your custom MyAnnotationProcessor (how?)
The processor scans your classpath for instances of #MyAnnotation
Typically, an annotation processor does dynamic bytecode injection, modifying/enhancing your compiled classes on-the-fly
Correct.
Correct.
Correct. Typically you will extend AbstractProcessor. You specify your MyAnnotationProcessor class using the ServiceLoader pattern - this makes it discoverable to the compiler. The Processor Javadoc contains some information on creating this class.
Correct.
This part is not correct. The annotation processor framework does not give you the ability to modify classes. You will need to use some post-compile process to do this as part of your build. What it does allow you to do is create new files. These may be simple resources, new Java source files (that will subsequently be required and eligible to the annotation processor during the same compile), or Java class files. You may also perform custom checks on source code and write errors to the log (causing the compile to fail).
I hope that addresses your understanding questions.
Are Java annotations used for adding functionality to Java code besides just adding documentation about what's going on in the code? What's the most advanced/complex functionality you could add to your code through an annotation?
Annotation are basically not more than a tag (with optional additional data) on a class/method/field. Other code (libraries or tools) can discover these tags and execute functionality dependant on the annotations found. I don't see a real limit on the complexity of the functionality possibly added by annotations. This can for example emulate AOP (adding functionality before or after a method with an annotation).
Annotations as such only add information (metadata) to a class.
One can easily build a system that uses that metadata to provide additional functionality, however.
For example you can use apt to generate classes based on the information provided by the annotation.
An annotation needs a tool to react to it. If such a tool does not exist the annotation is merely a notation. The "tool" can be an APT based agent or some piece of code that uses reflection (for instance, JUnit's #Test).
Several annotations are recognized by the Java compiler and thus have pre-defined semantics: #Override, #Deprecated, #Target.
I would understand Annotations as a way to document your code in a machine readable way.
For example in Hibernate you can specify the whole persistence information for your objects as annotations. This is directly readable for you and not in a distant xml file. But is also readable for the tool to generate configurations, database schemes etc.