简体   繁体   English

如何确定 javax.measure.Quantity 是否是速度?

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

I have some code that uses the javax.measure API to compute the speed of an asset being tracked.我有一些代码使用 javax.measure API 来计算被跟踪资产的速度。 I pass the Quantity object as a value into a JTable renderer and the generic parameter (Speed) has been erased.我将 Quantity object 作为值传递给 JTable 渲染器,通用参数(速度)已被删除。 Even if the Speed parameter were there, I would not be able to reflect on that to determine the type of Quantity.即使有 Speed 参数,我也无法对此进行反思以确定 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.我目前有滥用 asType() 方法的代码,但这似乎不像 API 应该如何使用。

// 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. 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.只有时间会证明它是否会带来有用的东西,尤其是现在谷歌刚刚在 SCOTUS 赢得了 Java 诉讼,胜过 Oracle。 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.虽然这对整个开源社区来说是一个非常好的迹象,但如果甲骨文未能按照其希望的方式通过对 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.我们已经对这些东西进行了很长时间的试验(在某些情况下超过 10 年),到目前为止 Java 语言所允许的仅此而已。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM