Explanation about Annotations - java

Can anyone please explain what the following two paragraphs mean, in simple english? (Taken from http://www.ibm.com/developerworks/java/library/j-cwt08025.html)
"Annotations are more flexible in
terms of how you use them, with
options for whether the annotation
information is to be included in class
files output by the compiler and made
available to the application at run
time"
Not sure what these means. Can Annotations be configured to optionally change the bytecode?
While annotations are ideal for
metadata that relates to a particular
component, they are not well suited to
metadata with cross-component
application.
IMHO most web applications would be cross-component ones. What is the author trying to say here?

Annotations are more flexible in terms
of how you use them, with options for
whether the annotation information is
to be included in class files output
by the compiler and made available to
the application at run time
This, I think, refers to the fact that Java5 annotations can be dropped by the compiler, whereas some can be retained in the bytecode. This is controlled by the #Retention annotation that is placed on your annotation type, e.g
#Documented
#Retention(value=RUNTIME)
public #interface Deprecated
This indicates that the #Deprecated annotation will be present in the bytecode, and will also be visible to reflection. java.lang.annotation.RetentionPolicy defines the different options.

"Annotations are more flexible in terms of how you use them, with options for whether the annotation information is to be included in class files output by the compiler and made available to the application at run time"
It is more flexible than XDoclet because:
it can be used from the source code (like XDoclet)
it can be used at runtime, when you only have the byte-code and not the source code (unlike XDoclet)
While annotations are ideal for metadata that relates to a particular component, they are not well suited to metadata with cross-component application.
Annotations (like XDoclet) have one interesting feature, as opposed to an external Xml for example :
Annotations live in the code, so it is natural for them to be applied to the code they are defined on. You don't have to specify (using some complex syntax) to what piece of code they apply. Examples:
if an annotation is defined on a method, it applies naturally to that method
if an annotation is defined on a field, it applies naturally to that field
if an annotation is defined on a class, it applies naturally to that class
if an annotation is defined on a package, it applies naturally to that package
If you want to have the same in an external Xml file, you have to use a complex syntax to identify the piece of code you refer to. So that makes them very easy to apply.
Also, in case of a code refactoring (like renaming), annotations continue to work just fine, while an external xml would have to be changed to point to the new class or method name.
I don't believe that in a web application, most things are cross-component.
If you defined Persistance (to a database) of an Entity, like what is the table where this class should be persisted, it is not something global to all Entities, it only affects the current Entity.
same for many other examples...

Related

Java annotation-based code injection without altering the annotated code

There is a Java application and I have no permission to alter the Java code apart from annotating classes or methods (with custom or existing annotations).
Using annotations and annotations only I have to invoke code which means that every time an instance of an annotated class is created or an annotated method is called, some extra Java code must be executed (e.g a call to a REST Webservice). So my question is: how can I do this?
In order to prevent answers that I have already checked I will give you some solutions that seem to work but are not satisfying enough.
Aspect Oriented Programming (e.g AspectJ) can do this (execute code before and after the call of an annotated method) but I don't really want the runtime overhead.
Use the solution provided here which actually uses reflection. This is exactly what I need only that it alters the initial code further than just annotating and so I cannot use it.
Use annotation processor for source code generation as suggested here by the last answer. However, still this means that I will alter the source code which I don't want.
What I would really like is a way to simply include a Java file that somehow will execute some Java lines every time the annotated element will be triggered.
Why not skip annotations completely and use byteman to inject code at runtime into the entry points of your code.
I have to agree with the comment above though, that this sort of restriction is ridiculous and should be challenged.

Using an Annotation Processor to create a list of classes with a certain annotation

I have a custom annotation that I've implemented and I'd like to use an annotation processor to generate a list of all the classes in my app that use that particular annotation.
I've found this tutorial which describes how to generate a class file using an annotation processor, so it should be quite easy to generate a class for each class with my annotation.
What I can't figure out is how I can collect all of that information into a single class. There doesn't seem to be a way to modify a class, so I can't append new items to the list once the class has been generated the first time.
Is there a way to use an annotation processor to generate a method that will return the list of all classes in an app that are annotated with a particular annotation?
Generated classes do not necessarily have to correspond one-to-one to the input classes being processed. Plus, you can search for classes (Elements) that are annotated with a given annotation via the RoundEnvironment:
roundEnvironment.getElementsAnnotatedWith(MyAnnotation.class)
From this you can generate a single class with a method that returns a collection of the classes found.
A couple issues around this to highlight:
Annotation processors can run along with other annotation processors and thus have to deal with classes generated at compile time. To aid this, Java annotation processing is performed in rounds to allow processors to catch the outputs of others. To be compatible with other processors you need to gracefully handle the ErrorType.
Only classes in the current compilation pass are returned from the RoundEnvironmnet methods so classes in external libraries will not be included.
IDEs (cough cough Eclipse) implement the annotation processing facilities of Java differently which can be a problem for processors that require a full non-partial compilation like I've described.
Coincidentally, I created a similar project recently that does what you are looking for:
https://github.com/johncarl81/silver
Silver is very much a WIP and uses a lot of library code to accomplish the task, but it may give you an idea for what's possible.

What is a good usecase for Guice Mapbinder?

I've seen it used, but I'm not sure the usage were good usecase examples. Do you have examples of idiomatic usages of Guice Mapbinder? (Cases where Mapbinder is really the correct tool to solve a problem)
Offhand, it looks like a reasonable way to create a registry of runtime-named implementations of a common interface. Consider selecting one of many plugins/modes/whatever from a command line or configuration file: the desired injection can't be known at compile time. A MapBinder provides an easy runtime lookup without resorting to type-switching.
I extensively use it in Guts-GUI.
You can take a look, in particular, at the ResourceModule, where it is used to map the right ResourceConverter<T> for a given type T:
Map<TypeLiteral<?>>, ResourceConverter<?>>
The MapBinder is directly created in the Resources helper class.
This way, any module can add its own resource converters for its own types, e.g. MessageModule adds its own converters.
I also used it as Map<Integer, WindowProcessor>> in WindowsModule to define an ordered list of WindowProcessors to be applied, one after another, to a newly created window..
Once again, this allows various modules to insert their own processor to the list applied to every window: ResourceModule uses it to add the ability of automatic injection of i18n resources to windows.

Arguments Against Annotations

My team is moving to Spring 3.0 and there are some people who want to start moving everything into Annotations. I just get a really bad feeling in my gut (code smell?) when I see a class that has methods like this: (just an example - not all real annotations)
#Transaction
#Method("GET")
#PathElement("time")
#PathElement("date")
#Autowired
#Secure("ROLE_ADMIN")
public void manage(#Qualifier('time')int time) {
...
}
Am I just behind the times, or does this all seem like a horrible idea to anyone else? Rather then using OO concepts like inheritance and polymorphism everything is now by convention or through annotations. I just don't like it. Having to recompile all the code to change things that IMO are configuration seems wrong. But it seems to be the way everything (especially Spring) is going. Should I just "get over it" or should I push back and try to keep our code as annotation free as possible?
Actually I think that the bad feeling in your gut against has more to do with Annotations like this mixing configuration with code.
Personally I feel the same way as you do, I would prefer to leave configuration (such as transaction definitions, path elements, URLs that a controller should be mapped to, etc.) outside of the code base itself and in external Spring XML context files.
I think though that the correct approach here comes down to opinion and which method you prefer - I would predict that half the community would agree with the annotations approach and the other half would agree with the external configuration approach.
Maybe you have a problem with redundant annotations that are all over the code. With meta-annotations redundant annotations can be replaced and your annotations are at least DRY.
From the Spring Blog:
#Service
#Scope("request")
#Transactional(rollbackFor=Exception.class)
#Retention(RetentionPolicy.RUNTIME)
public #interface MyService {
}
#MyService
public class RewardsService {
…
}
Because Java evolves so slowly people are putting more features that are missing in the language into annotations. This is a good thing Java can be extended in some form and this is a bad thing as most of the annotations are some workaround and add complexity.
I was also initially skeptical about annotations, but seeing them in use, they can be a great thing. They can also be over used.
The main thing to remember about annotations is that they are static. They cannot change at runtime. Any other configuration method (xml, self-description in code, whatever) does not suffer from this. I have seen people here on SO have issues with Spring in terms of having a test environment on injecting test configurations, and having to drop down to XML to get it done.
XML isn't polymorphic, inherited or anything else either, so it is not a step backwards in that sense.
The advantage of annotations is that it can give you more static checking on your configuration and can avoid a lot of verbosity and coordination difficulties in the XML configurations (basically keeping things DRY).
Just like XML was, Annotations can be over used. The main point is to balance the needs and advantages of each. Annotations, to the degree that they give you less verbose and DRYer code, are a tool to be leveraged.
EDIT: Regarding the comment about an annotation replacing an interface or abstract class, I think that can be reasonable at the framework boundary. In a framework intended to be used by hundreds, if not thousands of projects, having an interface or base class can really crimp things (especially a base class, although if you can do it with annotations, there is no reason you couldn't do it with a regular interface.
Consider JUnit4. Before, you had to extends a base class that had a setup and tear down method. For my point, it doesn't really matter if those had been on an interface or in a base class. Now I have a completely separate project with its own inheritance hierarchy, and they all have to honor this method. First of all, they can't have their own conflicting method names (not a big deal in a testing framework, but you get my point). Second of all you have have the chain of calling super all the way down, because all methods must be coupled.
Now with JUnit4, you can have different #Before methods in different classes in the hierarchy and they can be independent of each other. There is no equally DRY way to accomplish this without annotations.
From the point of view of the developers of JUnit, it is a disaster. Much better to have a defined type that you can call setUp and teardown on. But a framework doesn't exist for the convenience of the framework developer, it exists for the convenience of the framework user.
All of this applies if your code doesn't need to care about the type (that is, in your example, nothing would every really use a Controller type anyway). Then you could even say that implementing the framework's interface is more leaky than putting on an annotation.
If, however, you are going to be writing code to read that annotation in your own project, run far away.
It's 2018 and this point is still relevant.
My biggest problem with annotations is that you don't have an idea what the annotations are doing. You're cutting some caller code off and hiding it somewhere disconnected from the callee.
Annotations were introduced to make the language more declarative and less programmatic. But if you're moving the majority of the functionality to annotations, you are effectively switching your code to a different language (and not a very good one at that). There's very little compile-time checking. This article makes the same point: https://blog.softwaremill.com/the-case-against-annotations-4b2fb170ed67
The whole heuristic of "move everything to configuration so that people don't have to learn how to code" has gotten out of control. Engineering managers aren't thinking.
Exceptions:
JUnit
JAX-RS
I personally feel that annotations have taken over too much and have blown up from their original and super useful purpose (e.g., minor things like indicating overridden method) into this crazy metaprogramming tool. I don't feel the JAva mechanism is robust enough to handle these clusters of annotations preceding each method.
For instance, I'm fighting with JUnit annotations these days because they restrict me in ways that I don't like
That being said, in my experience the XML based configuration isn't pretty either. So to quote South Park, you're choosing between a giant douche and a t*rd sandwich.
I think that the main decision you have to make is whether you are more comfortable with having a delocalization of the spring configuration (i.e., maintain two files instead of one), and whether you use tools or IDE plugins that benefit from the annotations. Another important question is whether the developers who will use or maintain your code truly understand annotations.
Like many things, there are pros and cons. In my opinion, some annotations are fine, though sometimes it feels like there is a tendency to overuse annotations when a plain old function calling approach might be superior, and taken as a whole, this can unintentionally increase cognitive load because they increase the number of ways to "do stuff."
Let me explain. For example, I'm glad you mentioned the #Transactional annotation. Most Spring developers probably are going to know about and use #Transactional. But how many of those developers know how #Transactional actually works? And would they know off the top of their head how to create and manage a transaction without using the #Transactional annotation? Using #Transactional makes it easier for me to use transactions in a majority of cases, but in particular cases when I need more fine-grained control over a transaction, it hides those details from me. So in a way it is a double edged sword.
Another example is #Profile in Spring config classes. In the general case, it makes it easier to specify which profiles you want a Spring component loaded in. However, it if you need more powerful logic than just specifying a list of profiles for which you want the component loaded, you would have to get the Environment object yourself and write a function to do this. Again, most Spring developers would probably be familiar with #Profile, but the side effect of that is they become less familiar with the details of how it works, like the Environment.acceptsProfiles(String... profiles) function, for instance.
Finally, when annotations don't work, it can be harder to understand why and you can't just put a breakpoint on the annotation. (For instance, if you forgot the #EnableTransactionManagement on your config, what would happen?) You have to find the annotation processor and debug that. With a function calling approach, you can of course just put a breakpoint in the function.
Annotations have to be used sparingly. They are good for some but not for all. At least the xml configuration approach keeps the config in one file (or multiple) instead of spread all over the place. That would introduce (as I like to call it) crappy code organization. You will never see the full picture of the configuration if it is spread across hundreds of files.
Annotations often introduce dependencies where such dependencies do not belong.
I have a class which happens by coincidence to have properties which resemble the attributes from a table in an RDBMS schema. The class was created with this mapping in mind. There is clearly a relationship between the class and the table but I am happy to keep the class free from any metadata declaring that relationship. Is it right that this class makes a reference to a table and its columns in a completely different system? I certainly don't object to external metadata that associates the two and leaves each free of an understanding of the other. What did I gain? It is not as if metadata in the source code provides type safety or mapping conformance. Any verification tool that could analyze JPA annotations could equally well analyze hibernate mapping files. Annotations did not help.
At one contract, I had created a maven module with a package of implementations of interfaces from an existing package. It is unfortunate that this new package was one of many directories within a monolithic build; I saw it as something separate from the other code. Nonetheless, the team was using classpath scanning so I had to use annotations in order to get my component wired into the system. Here I did not desire centralized configuration; I simply wanted external configuration. XML configuration was not perfect because it conflated dependency wiring with component instantiation. Given that Rod Johnson didn't believe in component based development, this was fair. Nonetheless, I felt once again that annotations did not help me.
Let's contrast this with something that doesn't bother me: TestNG and JUnit tests. I use annotations here because I write this test knowing that I am using either TestNG or JUnit. If I replace one for the other, I understand that I will have to perform a costly transition that will stray close to a rewrite of the tests.
For whatever reason, I accept that TestNG, JUnit, QUnit, unittest, and NUnit owns my test classes. Under no circumstances does either JPA or Hibernate own those domain classes which happen to get mapped to tables. Under no circumstances does Spring own my services. I control my logical and physical packaging in order to isolate units which depend upon either. I want to ensure that a move away from one doesn't leave me crippled because of all the dependencies it left behind. Saying goodbye is always easier than leaving. At some point, leaving is necessary.
Check these answers to similar questions
What are the Pros/Cons of Annotations (non-compiler) compared to xml config files
Xml configuration versus Annotation based configuration
Basically it boils down to: Use both. Both of them have there usecases. Don't use annotations for things which should remain configurable without recompiling everything (especially things which maybe your user should be able to configure without needing you to recompile all)
I think it depends to some extent on when you started programming. Personally, I think they are horrid. Primarily because they have some quasi-'meaning' which you will not understand unless you happen to be aware of the annotation in question. As such they form a new programming language all by themselves and move you further away from POJOs. Compared to (say) plain old OO code. Second reason - they can prevent the compiler doing your work for you. If I have a large code base and want to refactor something or rename something I'd ideally like the compiler to throw up everything that needs to be changed, or as much as possible. An annotation should just be that. An annotation. Not central to the behaviour of your code. They were designed originally to be optionally omitted upon compilation which tells you all you need to know.
And yes, I am aware that XML config suffers in the same way. That doesn't make it worse, just equally bad. At least I can pretend to ignore that though - it doesn't stare me in the face in every single method or parameter declaration.
Given the choice I'd actually prefer the horrible old J2EE remote/home interfaces etc (so criticised by the Spring folks originally) as at least that gives me an idea of whats happening without having to research #CoolAidFrameworkThingy and its foibles.
One of the problems with the framework folks is that they need to tie you to their framework in order to make the whole enterprise financially viable. This is at odds with designing a framework well (i.e. for it to be as independant and removeable from your code as possible).
Unfortunately, though, annotations are trendy. So you will have a hard time preventing your team using them unless you are into code reviews/standards and the like (also, out of fashion!)
I read that Stroustup left annotations out of C++ as he feared they would be mis-used. Sometimes things go in the wrong direction for decades, but you can hope things will come full circle in time..
I think annotations are good if they are used with measure. Annotations like #WebService do a lot of work at deployment and run time, but they don't interfere in the class. #Cachexxx or #Transactional clearly interfere by creating proxies and a lot of artifacts, but I think they are under control.
Thing begin to mess when using Hibernate or JPA with annotations and CDI. Annotations grow a lot.
IMO #Service and #Repository are interferences of Spring in your application code. They make your application Spring dependant and only for Spring use.
The case of Spring Data Graph is another story. #NodeEntity, for instance, add methods to the class at build time to save the domain object. Unless you have Eclipse and Spring plugin you will errors because those methods don't exist in source code.
Configuration near the object has its benefits, but also a single configuration point. Annotations are good with measure, but they aren't good for everything, and definitively bad when there are as much annotation lines as source code lines.
I think the path Spring is going is wrong; mainly because in some cases there is no other way to do such funny things. It's is as if Spring wants to do xtreme coding, and at the same time they lock developers into Spring framework. Probably Java language needs another way to do some things.
Annotations are plain bad in my experience:
Inability to enforce type safety in annotations
Serialization issues
Cross compiling (to for instance javascript) can be an issue.
Libraries/frameworks requiring annotations exclude non-annotated classes from external libraries.
not overridable or interchangeable
your projects eventually becomes strongly dependant on the system that requires the annotations
If Java would have something like "method literals" you could annotate a class in a corresponding annotation class.
Something like as following:
Take for instance javax.persistence, and the following annotated class:
#Entity
class Person
{
#Column
private String firstname;
public String getFirstname() { return firstname; }
public void setFirstname(String value) { firstname = value; }
#Column
private String surname;
public String getSurname() { return surname; }
public void setSurname(String value) { surname = value; }
}
Instead of the annotations, I'd suggest a mapping class like:
class PersonEntity extends Entity<Person> {
#Override
public Class<Person> getEntityClass() { return Person.class;}
#Override
public Collection<PersistentProperty> getPersistentProperties() {
LinkedList<PersistentProperty> result = new LinkedList<>();
result.add(new PersistentProperty<Person>(Person#getFirstname, Person#setFirstname);
result.add(new PersistentProperty<Person>(Person#getSurname, Person#setSurname);
return result;
}
}
The fictional "#" sign in this pseudo java code represents a method literal, which, when invoked on an instance of the given class, invokes the corresponding delegate (signed with "::" since java 8) of that instance.
The "PersistentProperty" class should be able to enforce the method literals to be referring to the given generic argument, in this case the class Person.
This way, you have more benefits than annotations can deliver (like subclassing your 'annotate'-class) and you have none of the aforementioned cons.
You can have more domain-specific approaches too.
The only pre annotations have over this, is that with annotations you can quickly see whether you have forgotten to include a property/method. But this too can be handled more concise and more correct with better metadata support in Java (think for instance of something like required/optional like in Protocolbuffers)

How can I extend Java code generated by JAXB, CXF or Hibernate tools?

With generated Java source code, like
code generated with Hibernate tools
code generated with JAXB schema binding (xjc)
code generated with WDSL2Java (cxf)
all generated classes are "value object" types, without business logic. And if I add methods to the generated source code, I will loose these methods if I repeat the source code generation.
Do these Java code generation tools offer ways to "extend" the generated code?
For example,
to override the ToString method (for logging)
to implement the visitor pattern (for data analysis / validation)
For JAXB, see Adding Behaviours.
Basically, you configure JAXB to return a custom instance of the object you'd normally expect. In the below example you create a new object PersonEx which extends the JAXB object Person. This mechanism works well in that you're deriving from the generated classes, and not altering the JAXB classes or schemas at all.
package org.acme.foo.impl;
class PersonEx extends Person {
#Override
public void setName(String name) {
if(name.length()<3) throw new IllegalArgumentException();
super.setName(name);
}
}
#XmlRegistry
class ObjectFactoryEx extends ObjectFactory {
#Override
Person createPerson() {
return new PersonEx();
}
}
Note that the #Override directive is important in case your JAXB object changes - it will prevent your customisation becoming orphaned.
As for Hibernate you may tweak the template files used in code generation to change their behaviour. If you want to tweak the HIbernate Tools you can edit, for example: dao/daohome.ftl
You may even add fields to the "toString()" output editing the .hbm.xml files
...
<property name="note" type="string">
<meta attribute="use-in-tostring">true</meta>
<column name="note" />
</property>
...
Both for logging and validation you may consider using AOP with AspectJ (I don't recommend messing with the generated code, since you might want to build that from scratch many times over).
First I would reiterate that modification of generated code has many problems associated with it and that, where possible it should be avoided. That said sometimes this is impractical to avoid or more effort than just dealing with the changes when the code is regenerated.
Sadly java doesn't support the concept of partial classes that c# has. These are precisely to solve this sort of problem.
You should see if your code generation tools support some form of meaningful comments which delimit regions added by yourself in the class (this is unlikely and won't help if you are modifying the code rather than adding to it)
You best option if you really wish to do this is to generate the files initially but check them into a version control repository immediately.
Then make your changes, check that in.
Next time you rerun the tools and let them overwrite the existing files you can diff against your source controlled ones and merge the changes back in (most trivial changes like addition of new columns/tables will be little effort.
This will not help you as much if the code generator suddenly generates radically different code (say a new version) but in those cases any code you added which wasn't simply additional convenience methods relying on data/methods already exposed publicly) will have problems no matter how it is mixed into the class. The version control system does still help however since it also records the original changes so you can see what you had added previously and what, one would assume, you need to recreate in the new style.
It is not a good idea to edit generated code files, either by editing the files them selves or by subclassing. Whatever you do, be sure to leave the signature created by the tool intact, so that it will be possible to understand in the future that the file was auto-generated.
I recommend that you research the command options of the tools to see if they allow you some flexibility. Some tools can generate abstract classes or interfaces instead of concrete classes. If this is not possible, create a domain object that includes the autogenerated object as a member variable.
The way I have used Hibernate is to generate base classes that I then extend. I add all my business logic (if any) to these subclasses. I quite often also end up changing the FreeMarker templates used by Hibernate to further customize the generated classes.
The AOP citation is a good one. I'll add Spring, which has very nice AOP features built in.
Have a look at
http://code.google.com/p/jaxb-method-inserter/
Its a small plugin for JAXB I wrote, Its quite simple to uses. Hope it help

Categories