java 9中新的货币api-亚博电竞手机版

jsr 354定义了一套新的java货币api,计划会在java 9中正式引入。本文中我们将来看一下它的参考实现:javamoney的当前进展。

正如我在之前那篇java 8新的日期时间api一文中那样,本文主要也是通过一些代码来演示下新的api的用法 。

在开始之前,我想先用一段话来简短地总结一下规范定义的这套新的api的用意何在:

对许多应用而言货币价值都是一个关键的特性,但jdk对此却几乎没有任何支持。严格来讲,现有的java.util.currency类只是代表了当前iso

4217货币的一个数据结构,但并没有关联的值或者自定义货币。jdk对货币的运算及转换也没有内建的支持,更别说有一个能够代表货币值的标准类型了。

如果你用的是maven的话,只需把下面的引用添加到工里面便能够体验下该参考实现的当前功能了:

   org.javamoney   moneta   0.9 

规范中提到的类及接口都在javax.money.*包下面。

我们先从核心的两个接口currencyunit与monetaryamount开始讲起。

currencyunit及monetaryamount

currencyunit代表的是货币。它有点类似于现在的java.util.currency类,不同之处在于它支持自定义的实现。从规范的定义来看,java.util.currency也是可以实现该接口的。currencyunit的实例可以通过monetarycurrencies工厂来获取:

// 根据货币代码来获取货币单位 currencyunit euro = monetarycurrencies.getcurrency("eur");     currencyunit usdollar = monetarycurrencies.getcurrency("usd"); // 根据国家及地区来获取货币单位     currencyunit yen = monetarycurrencies.getcurrency(locale.japan); currencyunit     canadiandollar = monetarycurrencies.getcurrency(locale.canada);

montetaryamount代表的是某种货币的具体金额。通常它都会与某个currencyunit绑定。montetaryamount和currencyunit一样,也是一个能支持多种实现的接口。currencyunit与montetaryamount的实现必须是不可变,线程安全且可比较的。

/ get monetaryamount from currencyunit currencyunit euro = monetarycurrencies.getcurrency("eur"); monetaryamount fiveeuro = money.of(5, euro);  // get monetaryamount from currency code monetaryamount tenusdollar = money.of(10, "usd");  // fastmoney is an alternative monetaryamount factory that focuses on performance monetaryamount seveneuro = fastmoney.of(7, euro);

money与fastmoney是javamoney库中monetaryamount的两种实现。money是默认实现,它使用bigdecimal来存储金额。fastmoney是可选的另一个实现,它用long类型来存储金额。根据文档来看,fastmoney上的操作要比money的快10到15倍左右。然而,fastmoney的金额大小与精度都受限于long类型。

注意了,这里的money和fastmoney都是具体的实现类(它们在org.javamoney.moneta.*包下面,而不是javax.money.*)。如果你不希望指定具体类型的话,可以通过monetaryamountfactory来生成一个monetaryamount的实例:

monetaryamount specamount = monetaryamounts.getdefaultamountfactory()                 .setnumber(123.45) .setcurrency("usd") .create();

当且仅当实现类,货币单位,以及数值全部相等时才认为这两个montetaryamount实例是相等的。

monetaryamount oneeuro = money.of(1, monetarycurrencies.getcurrency("eur")); boolean isequal = oneeuro.equals(money.of(1, "eur")); // true boolean isequalfast = oneeuro.equals(fastmoney.of(1, "eur")); // false

monetaryamount内包含丰富的方法,可以用来获取具体的货币,金额,精度等等:

monetaryamount monetaryamount = money.of(123.45, euro); currencyunit currency = monetaryamount.getcurrency(); numbervalue numbervalue = monetaryamount.getnumber();  int intvalue = numbervalue.intvalue(); // 123 double doublevalue = numbervalue.doublevalue(); // 123.45 long fractiondenominator = numbervalue.getamountfractiondenominator(); // 100 long fractionnumerator = numbervalue.getamountfractionnumerator(); // 45 int precision = numbervalue.getprecision(); // 5  // numbervalue extends java.lang.number.  // so we assign numbervalue to a variable of type number number number = numbervalue;

monetaryamount的使用

可以在monetaryamount上进行算术运算:

monetaryamount twelveeuro = fiveeuro.add(seveneuro); // "eur 12" monetaryamount twoeuro = seveneuro.subtract(fiveeuro); // "eur 2" monetaryamount sevenpointfiveeuro = fiveeuro.multiply(1.5); // "eur 7.5"  // monetaryamount can have a negative numbervalue monetaryamount minustwoeuro = fiveeuro.subtract(seveneuro); // "eur -2"  // some useful utility methods boolean greaterthan = seveneuro.isgreaterthan(fiveeuro); // true boolean positive = seveneuro.ispositive(); // true boolean zero = seveneuro.iszero(); // false  // note that monetaryamounts need to have the same currencyunit to do mathematical operations // this fails with: javax.money.monetaryexception: currency mismatch: eur/usd fiveeuro.add(tenusdollar);

舍入操作是金额换算里面非常重要的一部分。monetaryamount可以使用舍入操作符来进行四舍五入:

currencyunit usd = monetarycurrencies.getcurrency("usd"); monetaryamount dollars = money.of(12.34567, usd); monetaryoperator roundingoperator = monetaryroundings.getrounding(usd); monetaryamount roundeddollars = dollars.with(roundingoperator); // usd 12.35

这里12.3456美金就会按当前货币默认的舍入规则来进行换算。

在操作monetaryamount集合时,有许多实用的工具方法可以用来进行过滤,排序以及分组。这些方法还可以与java 8的流api一起配套使用。

看一下下面这个集合:

list amounts = new arraylist<>(); amounts.add(money.of(2, "eur")); amounts.add(money.of(42, "usd")); amounts.add(money.of(7, "usd")); amounts.add(money.of(13.37, "jpy")); amounts.add(money.of(18, "usd"));

我们可以根据currencyunit来进行金额过滤:

currencyunit yen = monetarycurrencies.getcurrency("jpy"); currencyunit dollar = monetarycurrencies.getcurrency("usd"); // 根据货币过滤,只返回美金 // result is [usd 18, usd 7, usd 42] list onlydollar = amounts.stream()     .filter(monetaryfunctions.iscurrency(dollar))     .collect(collectors.tolist());  // 根据货币过滤,只返回美金和日元 // [usd 18, usd 7, jpy 13.37, usd 42] list onlydollarandyen = amounts.stream()     .filter(monetaryfunctions.iscurrency(dollar, yen))     .collect(collectors.tolist());

我们还可以过滤出大于或小于某个阈值的金额:

monetaryamount tendollar = money.of(10, dollar);  // [usd 42, usd 18] list greaterthantendollar = amounts.stream()     .filter(monetaryfunctions.iscurrency(dollar))     .filter(monetaryfunctions.isgreaterthan(tendollar))     .collect(collectors.tolist());

排序也是类似的:

// sorting dollar values by number value // [usd 7, usd 18, usd 42] list sortedbyamount = onlydollar.stream()     .sorted(monetaryfunctions.sortnumber())     .collect(collectors.tolist());  // sorting by currencyunit // [eur 2, jpy 13.37, usd 42, usd 7, usd 18] list sortedbycurrencyunit = amounts.stream()     .sorted(monetaryfunctions.sortcurrencyunit())     .collect(collectors.tolist());

还有分组操作:

// 按货币单位进行分组 // {usd=[usd 42, usd 7, usd 18], eur=[eur 2], jpy=[jpy 13.37]} map> groupedbycurrency = amounts.stream()     .collect(monetaryfunctions.groupbycurrencyunit());  // 分组并进行汇总 map summary = amounts.stream()     .collect(monetaryfunctions.groupbysummarizingmonetary()).get();  // get summary for currencyunit usd monetarysummarystatistics dollarsummary = summary.get(dollar); monetaryamount average = dollarsummary.getaverage(); // "usd 22.333333333333333333.." monetaryamount min = dollarsummary.getmin(); // "usd 7" monetaryamount max = dollarsummary.getmax(); // "usd 42" monetaryamount sum = dollarsummary.getsum(); // "usd 67" long count = dollarsummary.getcount(); // 3

monetaryfunctions还提供了归约函数,可以用来获取最大值,最小值,以及求和:

list amounts = new arraylist<>(); amounts.add(money.of(10, "eur")); amounts.add(money.of(7.5, "eur")); amounts.add(money.of(12, "eur"));  optional max = amounts.stream().reduce(monetaryfunctions.max()); // "eur 7.5" optional min = amounts.stream().reduce(monetaryfunctions.min()); // "eur 12" optional sum = amounts.stream().reduce(monetaryfunctions.sum()); //

自定义的monetaryamount操作

monetaryamount还提供了一个非常友好的扩展点叫作monetaryoperator。monetaryoperator是一个函数式接口,它接收一个monetaryamount入参并返回一个新的monetaryamount对象。

// a monetary operator that returns 10% of the input monetaryamount // implemented using java 8 lambdas monetaryoperator tenpercentoperator = (monetaryamount amount) -> {   bigdecimal baseamount = amount.getnumber().numbervalue(bigdecimal.class);   bigdecimal tenpercent = baseamount.multiply(new bigdecimal("0.1"));   return money.of(tenpercent, amount.getcurrency()); };  monetaryamount dollars = money.of(12.34567, "usd");  // apply tenpercentoperator to monetaryamount monetaryamount tenpercentdollars = dollars.with(tenpercentoperator); // usd 1.234567

标准的api特性都是通过monetaryoperator的接口来实现的。比方说,前面看到的舍入操作就是以monetaryoperator接口的形式来提供的。

汇率

货币兑换率可以通过exchangerateprovider来获取。javamoney自带了多个不同的exchangerateprovider的实现。其中最重要的两个是ecbcurrentrateprovider与 imfrateprovider。

ecbcurrentrateprovider查询的是欧洲中央银行(european central bank,ecb)的数据而imfrateprovider查询的是国际货币基金组织(international monetary fund,imf)的汇率。

// get the default exchangerateprovider (compoundrateprovider) exchangerateprovider exchangerateprovider = monetaryconversions.getexchangerateprovider();  // get the names of the default provider chain // [ident, ecb, imf, ecb-hist] list defaultproviderchain = monetaryconversions.getdefaultproviderchain();  // get a specific exchangerateprovider (here ecb) exchangerateprovider ecbexchangerateprovider = monetaryconversions.getexchangerateprovider("ecb");

如果没有指定exchangerateprovider的话返回的就是compoundrateprovider。compoundrateprovider会将汇率转换请求委派给一个exchangerateprovider链并将第一个返回准确结果的提供商的数据返回。

// get the exchange rate from euro to us dollar exchangerate rate = exchangerateprovider.getexchangerate("eur", "usd");  numbervalue factor = rate.getfactor(); // 1.2537 (at time writing) currencyunit basecurrency = rate.getbasecurrency(); // eur currencyunit targetcurrency = rate.getcurrency(); // usd

货币转换

不同货币间的转换可以通过exchangerateprovider返回的currencyconversions来完成。

// get the currencyconversion from the default provider chain currencyconversion dollarconversion = monetaryconversions.getconversion("usd");  // get the currencyconversion from a specific provider currencyconversion ecbdollarconversion = ecbexchangerateprovider.getcurrencyconversion("usd");  monetaryamount teneuro = money.of(10, "eur");  // convert 10 euro to us dollar  monetaryamount indollar = teneuro.with(dollarconversion); // "usd 12.537" (at the time writing)

请注意currencyconversion也实现了monetaryoperator接口。正如其它操作一样,它也能通过monetaryamount.with()方法来调用。

格式化及解析

monetaryamount可以通过monetaryamountformat来与字符串进行解析/格式化。

// formatting by locale specific formats monetaryamountformat germanformat = monetaryformats.getamountformat(locale.germany); monetaryamountformat usformat = monetaryformats.getamountformat(locale.canada);  monetaryamount amount = money.of(12345.67, "usd");  string usformatted = usformat.format(amount); // "usd12,345.67" string germanformatted = germanformat.format(amount); // 12.345,67 usd  // a monetaryamountformat can also be used to parse monetaryamounts from strings monetaryamount parsed = germanformat.parse("12,4 usd");

可以通过amountformatquerybuilder来生成自定义的格式。

// creating a custom monetaryamountformat monetaryamountformat customformat = monetaryformats.getamountformat(     amountformatquerybuilder.of(locale.us)         .set(currencystyle.name)         .set("pattern", "00,00,00,00.00 ¤")         .build());  // results in "00,01,23,45.67 us dollar" string formatted = customformat.format(amount);

注意,这里的¤符号在模式串中是作为货币的占位符。

总结

新的货币api这里已经介绍得差不多了。并且目前它的实现也已经相对稳定了(但还需要多补充些文档)。期待能在java 9中看到这套新的接口!

上述示例可在github中下载到。

展开全文
内容来源于互联网和用户投稿,文章中一旦含有亚博电竞手机版的联系方式务必识别真假,本站仅做信息展示不承担任何相关责任,如有侵权或涉及法律问题请联系亚博电竞手机版删除

最新文章

网站地图