Why are final classes unproxyable with CDI?
Asked Answered
G

2

5

Section 5.4.1 of the CDI spec states that otherwise valid beans are unproxyable (and thus cannot be injected) if declared final. The spec gives no rationale and I can not think of a reason for this decision.

I am trying to stick by design rules saying that classes not explicitly designed for inheritance should forbid it. So the CDI spec seems to enforce bad design (and makes CheckStyle cry).

Why is it so and what can be done about it?

Thank you.

Goncourt answered 23/5, 2012 at 14:22 Comment(0)
S
7

Because when you create a proxy for a class you inherit from it (or implement an interface, if possible) so if your class is final it can not be inherited from and no proxy can be created for it.

If you want to use CDI you need to have a non-final class. The other option is not use CDI altogether.

Speller answered 23/5, 2012 at 14:31 Comment(1)
Thank you for a clear answer, Mauricio. I ended with reluctantly disabling the according checkstyle module. Abandoning CDI is not a real option IMO :) Feels rather uncomfortable trading clean design against functionality.Goncourt
C
1

The only way to use method interception techniques on final classes is by changing the classes themselves. This used to be done through a process known as "enhancement" where the class files would be changed on disk; today we can use something called load-time weaving. This is a technique that changes the class while loading it. AspectJ uses this technique.

Chalmers answered 23/5, 2012 at 14:38 Comment(1)
Thank you Marko. So at least it could be done, though the chance that the next version of CDI will solve it is rather slim.Goncourt

© 2022 - 2024 — McMap. All rights reserved.