七種武器:apache commons : commons-lang

前言

有人說apache 就是丐幫,各種開源項目魚龍混雜,參差不起。

今天試着梳理下commons包,首先是commons-lang。

看了一眼之後,一個字:雜,有如瑞士軍刀,用途多而雜。

 

如何organize這種類JDK util代碼?

1) the most interesting in design or implementation

2) the most useful 

3) see how other developer uses, wrap, rewrite JDK

正文

lang.builder.*

解決了一個問題,實現以下四個methods時,如果一個class有很多fields,會是一件煩瑣和boring的工作。

  • equals
  • toString
  • hashCode
  • compareTo

example code

 

 

 

lang.reflect.*

MethodUtils

 

getMatchingAccessibleMethod

Find an accessible method that matches the given name and has compatible parameters. Compatible parameters mean that every method parameter is assignable from the given parameters. In other words, it finds a method with the given name that will take the parameters given.

 

This method can match primitive parameter by passing in wrapper classes. For example, a Boolean will match a primitive boolean parameter.

 

用在invokeMethod中, 使用isAssignableFrom, 實現代碼如下:

 

 

getAccessibleMethod

 

Return an accessible method (that is, one that can be invoked via reflection) with given name and parameters. If no such method can be found, return null.

用在invokeExactMethod中,主要實現代碼如下,getDeclaredMethod 和 getSuperclass 來遞歸實現

 


invokeExactMethod

Invoke a static method whose parameter types match exactly the parameter types given.

這個方法和invokeMethod的區別見下面的例子


invokeExactStaticMethod

  Invoke a named static method whose parameter type matches the object type.

靜態方法invoke時候,第一個object參數傳入null即可 method.invoke(null, args);

 

getMethods 返回所有public的member methods,包括繼承的父類和實現的接口中的方法。因此,靜態方法也包含在內。


invokeMethod

 

 Invoke a named method whose parameter type matches the object type.

 

lang.time.*

FastDateFormat
SimpleDateFormat is not thread-safe in any JDK version, nor will it be as Sun have closed the bug/RFE.
why SimpleDateFormat 什麼不是線程安全?因爲有些field是mutable

有很多解決方法,

每次new 加上synchronize 使用thread-local,和每次new差不多;如果線程重用,則減少了new的次數 使用object-pool,共享多個對象

StopWatch

lang.text.*

StrSubstitutor 

用來替換佔位符

 

StrTokenizer(對應guava中的splitter)

StrMatcher (對應guava中的CharMatcher)

StrBuilder (對應guava中的Joiner)

lang.*

WordUtils

用來capitalize 

 

StringUtils

有Join 也有split

 

ArrayUtils

nullToEmpty: Defensive programming technique,將null數組轉換成empty(size 爲0)的數組。

add/remove: 數組添加或者刪除元素

lang.math.* lang.exception.*

JVMRandom: ShardSeedRandom, 比Random要快??

RandomUtils

參考

http://www.slideshare.net/tcurdt/apache-commons-dont-reinvent-the-wheel-presentation

 

http://commons.apache.org/lang/userguide.html

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章