I need to be able to mark methods so that they throw a RuntimeException if they are called more than once.
I am trying to enforce some single assignment semantics and the number of parameters to my class is too large to put in a single constructor and I need to be able to make these classes JAXB
aware as well, so the objects need to be mutable but I want to enforce single assignment semantics.
I am pretty sure I can do this with Aspects, but I would really like to be able to use my own Annotations processor instead.
I know how to do this with Decorators in Python.
How do I write an Annotation processor that can intercept calls to the annotated method at runtime and not just at compile time?
I think I am on to something with with Dynamic Proxies intercepting the method calls, I just need to figure out how to integrate them with my Annotation processor.
Dynamic Proxies require you to use an Interface, that is way to cumbersome, I have a CGLib MethodInterceptor working now, much less requirements on what gets intercepted and decorated, at the expense of adding a dependency.
Nope, there's nothing ready-to-use. And AspectJ seems the only way to make it work in a more general manner. As JB Nizet noted - the annotation should have a parser to parse it.
However, I would advise for a better and simpler solution - the Builder pattern. What does it look like:
FooBuilder
(it may also be a static inner class) which is mutable and has a setter and getter for each of the fieldsFooBuilder
has abuild()
method that returns an instance ofFoo
Foo
has a constructor that takes onlyFooBuilder
, and you assign each field there.That way:
Foo
is immutable, which is your end goalIt is easy to use. You only set the fields that you need. Something like:
That way the builder can be JAXB-aware. For example:
JAXB objects need to be mutable, and your requirement is an immutable object. Hence the builder comes handy to bridge that.