Java - Creating a Pseudo Native Type

女生的网名这么多〃 提交于 2019-12-11 17:26:04

问题


In stock trading, quantities are usually integers (e.g. 5x shares, 10x options, etc). With cryptocurrencies, quantities are fractions (e.g. 0.01 bitcoin). In both scenarios, there is typically a minimum unit (e.g. multiples of 100x shares).

I would like to wrap this logic in a Quantity class. However:

  • Java native types (e.g. double) are final, so I cannot extend them
  • Java does not support operator overloading, so arithmetic will be ugly
  • Java does not support typedefs, so I cannot wrap a double with a Quantity type

So I guess my question is this, if I want to create something akin to a native type (lots of instances, pass-by-value, lots of arithmetic), is there a "classic" Java solution? From memory, C# has a struct type which is pass-by-value, is there something similar in Java?

Thank you,

EDIT: Is it possible to import a native type from C++ code, and effectively bypass Java?


回答1:


Yes, it is possible to declare typedefs in Java, with a guarantee of type-correctness, but without the syntactic complexity and run-time overhead of declaring a new Java class.

As a user, you can do this by writing a type annotation and using an annotation processor at compile time. For example, you would write @Quantity int for quantities, and you would compile with javac -processor QuantityProcessor MyFile.java. You can use any arithmetic operation on a @Quantity int, and the compiler issues a warning if you mix regular ints with @Quantity ints, or if there are other errors such as a value not being in the right range or not being a multiple of 100.

Someone needs to define the type annotations and the annotation processor, and because your requirements are unique, you will probably need to create your own. One framework that makes it easy to do create type annotations and annotation processors is the Checker Framework. (Disclosure: I am a developer.)

The following parts of the Checker Framework manual may be particularly helpful.

  • Type aliases and typedefs
  • Fake enumerations
  • How to create a new checker


来源:https://stackoverflow.com/questions/48938276/java-creating-a-pseudo-native-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!