Why are final classes unproxyable with CDI?

1.4k Views Asked by At

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.

2

There are 2 best solutions below

1
On BEST ANSWER

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.

1
On

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.