问题
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
) arefinal
, 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 aQuantity
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 int
s with @Quantity int
s, 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