七种武器: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

 

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

FireCoder

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值