Let's say I'd like to ensure type safety in Java on primitive types. For the sake of an example, let us want to distinguish a Ratio
from an AbsoluteValue
, both are represented by a double
.
Java to my best knowledge does not support type synonyms.
So I'm quite confident some overhead will be involved.
From the top of my head I could think of either defining new calsses which wrap double
(a lot of boilerplate), or subclassing Double
... or maybe there are even other options?
Which approach gives me the least performance overhead?
EDIT: I'm confined to Java 8, so that's the implicit basis of the question; however, if there are alternative solutions in newer versions of the language I'd still be keen to hear about them.
The most performant way I can think of would be to write your own wrapper classes which have some marker annotation:
@PrimitiveTypeAlias(double.class)
public class Milliseconds
{
double value() { ... }
}
Then hook into the annotation processor at compile-time and physically replace the wrapper classes with their primitive counterparts (using something like Lombok).
... But I suspect you may have been implying "most performant and also low-effort" :)
Take a look a Manifold framework (like Lombok but more concerned with Types than boilerplate reduction). @Extension
methods or @Structural
interfaces provide various ways of implementing "duck typing" which covers some of the requirement. It won't work directly with primitive fields though. A very basic wrapper class may be optimised by the JIT in various cases (and will be able to use Project Valhalla's inline
modifier when that lands).
(I suspect it is a reasonable feature-request to implement first-class aliases to complement Manifold's existing feature set.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With