How can I determine if a javax.measure.Quantity is a Speed?

12 views
Skip to first unread message

Gene McCulley

unread,
Apr 5, 2021, 1:41:56 PM4/5/21
to units...@googlegroups.com
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.

(I have also asked this on StackOverflow: https://stackoverflow.com/questions/65150100/how-can-i-determine-if-a-javax-measure-quantity-is-a-speed)

// 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);
}

Werner Keil

unread,
Apr 5, 2021, 1:48:17 PM4/5/21
to Units Users
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.

Chapman Flack

unread,
Apr 5, 2021, 2:25:37 PM4/5/21
to units...@googlegroups.com
On 04/05/21 13:32, Gene McCulley wrote:
> 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 currently have code that abuses the asType() method

I would think that q.getUnit().isCompatible(YOUR_FAVORITE_UNIT_OF_SPEED)
would be an appropriate test. It seems to be essentially the same test
that asType() would do in the reference implementation, minus the overhead
of constructing and catching a ClassCastException.

Regards,
-Chap

Werner Keil

unread,
May 14, 2021, 8:25:04 AM5/14/21
to Units Users
Hi,

This unfortunately is a problem Java still has. That Medium blog:
from last year summarizes it well. There are other languages even on the JVM that do a slightly better job at this than Java, but until the OpenJDK team has different priorities (e.g. yet another JIT Compiler, Garbage Collector or 50 different of() methods in types like List or Set) I'm afraid it will stay that way for Java.

So using asType() or isCompatible() (the latter for a particular Unit not just a Quantity type) are currently the only ways you can mainly use type checks that work (the ones for the generic type simply don't exist or they produce a nonsense answer like "Q") until the Java language came up with something better some day.

Regards,
Werner
Reply all
Reply to author
Forward
0 new messages