今天的帖子將帶我們了解Project Coin的每個功能-一系列小的語言增強功能,這些功能雖然不是開創性的,但是對于任何能夠使用JDK 7的開發人員來說都是有用的。
我提出了一個銀行帳戶課程,該課程展示了Project Coin功能的基礎知識。
看一看…
public class ProjectCoinBanker {private static final Integer ONE_MILLION = 1_000_000;private static final String RICH_MSG = "You need more than $%,d to be considered rich.";public static void main(String[] args) throws Exception {System.out.println(String.format(RICH_MSG, ONE_MILLION));String requestType = args[0];String accountId = args[1];switch (requestType) {case "displayBalance":printBalance(accountId);break;case "lastActivityDate" :printLastActivityDate(accountId);break;case "amIRich" :amIRich(accountId);break;case "lastTransactions" :printLastTransactions(accountId, Integer.parseInt(args[2]));break;case "averageDailyBalance" :printAverageDailyBalance(accountId);break;default: break;}}private static void printAverageDailyBalance(String accountId) {String sql = String.format(AVERAGE_DAILY_BALANCE_QUERY, accountId);try (PreparedStatement s = _conn.prepareStatement(sql);ResultSet rs = s.executeQuery();) {while (rs.next()) {//print the average daily balance results}} catch (SQLException e) {// handle exception, but no need for finally to close resourcesfor (Throwable t : e.getSuppressed()) {System.out.println("Suppressed exception message is " + t.getMessage());}}}private static void printLastTransactions(String accountId, int numberOfTransactions) {List transactions = new ArrayList<>();//... handle fetching/printing transactions}private static void printBalance(String accountId) {try {BigDecimal balance = getBalance(accountId);//print balance} catch (AccountFrozenException | ComplianceViolationException | AccountClosedException e) {System.err.println("Please see your local branch for help with your account.");}}private static void amIRich(String accountId) {try {BigDecimal balance = getBalance(accountId);//find out if the account holder is rich} catch (AccountFrozenException | ComplianceViolationException | AccountClosedException e) {System.out.println("Please see your local branch for help with your account.");}}private static BigDecimal getBalance(String acccountId)throws AccountFrozenException, AccountClosedException, ComplianceViolationException {//... getBalance functionality}}
簡要地說,我們的ProjectCoinBanker類演示了以下Project Coin功能的基本用法。
- 數字文字下劃線
- 開關中的弦
- 多漁獲
- 用于創建類型化對象的類型推斷
- 嘗試使用資源和抑制的異常
首先,數字文字中的下劃線很容易解釋。 我們的例子
private static final Integer ONE_MILLION = 1_000_000;
表明好處是視覺的。 開發人員可以快速查看代碼以驗證值是否符合預期。 下劃線可以在自然分組位置以外的其他地方使用,無論放置在何處。 數字文字中的下劃線不能以數字文字開頭或結尾,否則,您可以隨意將它們放在所需的位置。 盡管此處未進行演示,但還添加了二進制文字支持。 與十六進制文字以0x或0X前綴相同的方式,二進制文字將以0b或0B前綴。
開關中的字符串也是不言自明的。 現在,switch語句也接受String。 在我們的示例中,我們打開傳遞給main方法的String參數來確定發出了什么請求。 附帶說明,這純粹是一個編譯器實現,帶有指示,可能會在以后添加JVM對String的支持。
類型推斷是另一個易于理解的改進。 現在代替我們的舊代碼
List<Transaction> transactions = new ArrayList<Transaction>();
我們可以做
List<Transaction> transactions = new ArrayList<>();
因為可以推斷類型。 自從引入泛型以來,可能找不到任何人會辯稱不應該這樣做,但是現在就在這里。
多次捕獲對于異常處理代碼的簡潔性來說非常有用。 想要實際基于拋出的異常類型來做某事的次數太多了,直到現在,我們被迫擁有多個catch塊,它們基本上都在做同一件事。 新語法非常干凈和合乎邏輯。 我們的例子
catch (AccountFrozenException | ComplianceViolationException | AccountClosedException e)
顯示了如何輕松完成。
最后,Project Coin功能的最后一個演示是嘗試使用資源語法并支持檢索抑制的異常。 引入了一個新的接口AutoCloseable ,該接口已應用于所有預期的可疑對象,包括Input / OutputStreams,讀取器/編寫器,通道,套接字,選擇器和java.sql資源Statement,ResultSet和Connection。 在我看來,語法不像多捕獲更改那樣自然,并不是說我有其他選擇。
try (PreparedStatement s = _conn.prepareStatement(sql);ResultSet rs = s.executeQuery();) {while (rs.next()) {//print the average daily balance results}} catch (SQLException e) {//handle exception, but no need for finally to close resourcesfor (Throwable t : e.getSuppressed()) {System.out.println("Suppressed exception message is " + t.getMessage());}}
首先,我們看到可以在嘗試使用資源時包含多個資源-非常好。 我們甚至可以在與PreparedStatement相同的塊中引用先前聲明的資源。 我們仍然可以處理我們的異常,但是我們不需要關閉finally塊來關閉資源。 還要注意, Throwable上有一個新方法getSuppressed() 。 這使我們可以訪問試圖“自動關閉”聲明的資源時拋出的所有異常。 每個聲明的資源最多可以有一個抑制的異常。 注意:如果資源初始化引發異常,它將在聲明的catch塊中處理。
而已。 沒有什么破天荒的事情,但是我們可以不用太多麻煩就可以開始使用的一些簡單增強功能。 Project Coin還包括有關varargs和編譯器警告的功能。 本質上,它歸結為一個新的注釋(@SafeVarargs),可以在方法聲明中應用該注釋,以允許開發人員從其使用的代碼中刪除@SuppressWarnings(“ varargs”)。 這已應用于JDK中的所有關鍵可疑對象,但是在任何通用varags方法中都可以使用相同的注釋。
在線描述的項目代幣功能集充其量是不一致的。 希望這會給您關于JDK 7提案中可以使用的內容的完整摘要。
參考: JCG合作伙伴的 Java 7 –項目硬幣功能概述 在Carfey Software Blog上 。
- Java 7:嘗試資源
- 具有Java 7中自動資源管理功能的GC
- 速覽Java 7 MethodHandle及其用法
- 在Java 7中處理文件
- Java SE 7、8、9 –推進Java
- Java教程和Android教程列表
翻譯自: https://www.javacodegeeks.com/2011/11/java-7-feature-overview.html