Creating a Util Class

I created a fomatter currency class. I want this to be a util class and can be used by other applications. Now I just take a string, instead I want it to be installed by an application importing my currencyUtil.jar

 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; } } 

Let another application that calls this util class be

  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 } 

What changes am I making?

+4
source share
2 answers

You need to create an object of class CurrencyUtil .

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

I suggest the currenyUtil method should be static and it takes three parameters.

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

and you can call him

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

According to Joshua Bloch's "Effective Java," Point 4: Ensure Intuitiveness Using a Private Constructor:

 public final class CurrencyUtil { // A private constructor private CurrencyUtil() { throw new AssertionError(); } //Here goes your methods } 
0
source

Source: https://habr.com/ru/post/1388911/


All Articles