I have some code that uses the javax.measure API to compute the speed of an asset being tracked. I pass the Quantity object as a value into a JTable renderer and the generic parameter (Speed) has been erased. Even if the Speed parameter were there, I would not be able to reflect on that to determine the type of Quantity. How do I determine that the Quantity is a Speed? I want to render the value differently when it is a speed. I currently have code that abuses the asType() method, but that does not seem like how the API should be used.
// FIXME: This seems hokey. There should be a better way.
public static <C extends Quantity<C>> boolean isOfType(final Quantity<?> q, final Class<C> c) {
try {
q.asType(c);
return true;
} catch (final ClassCastException e) {
return false;
}
}
public static boolean isSpeed(final Quantity<?> q) {
return isOfType(q, Speed.class);
}
I would say, this is probably the best you can do in Java at the moment because generic types are extremely limited compared to C# or even languages like Kotlin on the JVM.
While it sounded promising in that direction Project Valhalla has been extremely disapointing so far both regarding what it offered in the first previews and the overall pace. Only time will tell, if it ever leads to something useful, especially now that Google won the Java lawsuit over Oracle at the SCOTUS just today. And while this is a very good sign for the Open Source community as a whole, it may further decrease Oracle's contribution if it fails to monetize it the way it may have hoped by charging license fees even for Android.
So while this approach may seem a bit weird and uninuitive, I'm afraid, that is all you can do at the moment. We experimented with these kinds of things for a long time now (over 10 years in some cases) and so far what the Java language allows is not much more than this.