2012-01-02 42 views
4

我已經創建了一個貨幣fomatter類。我希望這是一個util類,可以被其他應用程序使用。 現在我只是走一個字符串,而不是我希望它由應用程序導入我的currencyUtil.jar創建一個Util類

public class CurrencyUtil{ 
    public BigDecimal currencyUtil(RenderRequest renderRequest, RenderResponse renderResponse) 
     throws IOException, PortletException { 
     BigDecimal amount = new BigDecimal("123456789.99"); //Instead I want the amount to be set by the application.  
     ThemeDisplay themeDisplay = 
      (ThemeDisplay)renderRequest.getAttribute(WebKeys.THEME_DISPLAY); 
     Locale locale = themeDisplay.getLocale(); 

     NumberFormat canadaFrench = NumberFormat.getCurrencyInstance(Locale.CANADA_FRENCH); 
     NumberFormat canadaEnglish = NumberFormat.getCurrencyInstance(Locale.CANADA); 
     BigDecimal amount = new BigDecimal("123456789.99"); 
     DecimalFormatSymbols symbols = ((DecimalFormat) canadaFrench).getDecimalFormatSymbols(); 
     symbols.setGroupingSeparator('.'); 
     ((DecimalFormat) canadaFrench).setDecimalFormatSymbols(symbols); 

    System.out.println(canadaFrench.format(amount)); 
     System.out.println(canadaEnglish.format(amount));  
    //Need to have a return type which would return the formats 
    return amount; 
    } 
} 

讓它調用其他應用程序中設置這個UTIL類是

import com.mypackage.CurrencyUtil; 
... 
public int handleCurrency(RenderRequest request, RenderResponse response) { 
String billAmount = "123456.99"; 
    CurrencyUtil CU = new currencyUtil(); 
//Need to call that util class and set this billAmount to BigDecimal amount in util class. 
//Then it should return both the formats or the format I call in the application. 
    System.out.println(canadaEnglish.format(billAmount); //something like this 
} 

我做出什麼樣的變化?

+0

我會做的效用如果可以的話,這個類是無狀態的,你不需要創建一個實例,它的所有方法都是靜態的。 – 2012-01-02 11:13:26

回答

1

您需要創建CurrencyUtil類的對象。

CurrencyUtil CU = new CurrencyUtil(); 
//To call a method, 
BigDecimal value=CU.currencyUtil(request,response); 

我建議currenyUtil方法應該是static,它需要三個參數。

public class CurrencyUtil 
{ 
    public static BigDecimal currencyUtil(
       RenderRequest renderRequest, 
       RenderResponse renderResponse, 
       String amountStr) throws IOException, PortletException 
    { 
     BigDecimal amount = new BigDecimal(amountStr); 
     ... 
    } 
} 

,你可以稱呼它,

BigDecimal value=CurrencyUtil.currencyUtil(request,response,billAmount); 
+0

如果我想將返回類型更改爲ArrayList 那麼我的BigDecimal量如何改變其類型轉換。 (ArrayList amountStr){ 'BigDecimal amount = new BigDecimal(ArrayList amountStr); //我如何讀取數量,其中參數不是字符串,而是數組列表 \t return amountStr; \t}' – 2012-01-03 07:11:37

0

根據有效的Java由約書亞布洛赫, 項目4:強制noninstantiability與私有構造:

public final class CurrencyUtil { 

    // A private constructor 
    private CurrencyUtil() { 
     throw new AssertionError(); 
    } 

    //Here goes your methods 
}