Back

(java 往日的翻译) Commons Lang user guide.

发布时间: 2008-05-07 06:32:00

he Commons Lang Package
Users Guide 使用指南
Description 概述
The Commons Lang library provides much needed additions to the standard JDK's java.lang package. Very generic, very reusable components for everyday use.
Commons Lang 类库是对标准JDK的 java.lang包的一个必要补充。提供了我们日常工作用到的广泛的,可重用的组件。
The top level package contains various Utils classes, whilst there are various subpackages including enums, exception and builder. Using the Utils classes is generally simplicity itself. They are the equivalent of global functions in another language, a collection of stand-alone, thread-safe, static methods. In contrast, subpackages may contain interfaces which may have to be implemented or classes which may need to be extended to get the full functionality from the code. They may, however, contain more global-like functions.
顶层包包含了多个工具类,同时多个子包含有enum(枚举),exception (异常)和builder(构造器)。使用起来非常容易。它们由其他语言的本地函数,独立的集合,静态方法组成,而且是thread-safe的(线程安全)。另一方面,子包中的一些接口需要您亲自实现或者扩展。它们也许包含了多个global-like(全局性的)函数。

Lang seeks to support Java 1.2 onwards, so although you may have seen features in later versions of Java, such as split methods and nested exceptions, Lang still maintains non-java.lang versions for users of earlier versions of Java.
Lang包支持Java1.2以前的版本。尽管我们会看到如split method或nested exception这样的新版本Java特性,但Lang仍然会支持早期Java版本。
You will find deprecated methods as you stroll through the Lang documentation. These are removed in the next major release.
通读Lang文档会发现一些不建议使用的方法,它们将不会出现在下个主要版本中。
Before we begin, it's a good time to mention the Utils classes. They all contain empty public constructors with warnings not to use. This may seem an odd thing to do, but it allows tools like Velocity to access the class as if it were a bean. In other words, yes we know about private constructors.
在开始之前,最好提一下工具类。它们都包含了空的public constructor,并且标明不要使用。它不是多余的东东,是为了可以把它作为一个bean,让Velocity等工具可以调用。换句话说,我们知道 private constructor.(?)
lang.*
String manipulation - StringUtils, StringEscapeUtils, RandomStringUtils, Tokenizer, WordUtils
Lang has a series of String utilities. The first is StringUtils, oodles and oodles of functions which tweak, transform, squeeze and cuddle java.lang.Strings. In addition to StringUtils, there are a series of other String manipulating classes; RandomStringUtils, StringEscapeUtils and Tokenizer. RandomStringUtils speaks for itself. It's provides ways in which to generate pieces of text, such as might be used for default passwords. StringEscapeUtils contains methods to escape and unescape Java, JavaScript, HTML, XML and SQL. Tokenizer is an improved alternative to java.util.StringTokenizer.
Lang包有一系列的String工具类。首先就是StringUtils,包括了各种压缩,转换,截取java.lang.String的各种操作。另外还有其他的String操作类,作为对StringUtils的补充:RandomStringUtils, StringEscapeUtils and Tokenizer. 从名字就可以看出来(不言而喻),RandomStringUtils是为了生成成随机字符串的,例如用在默认密码的场合。StringEscapeUtils包含了多个方法来生成 Java, JavaScript, HTML, XML和SQL的脱离符。Tokenizer则是StringTokenizer的改进类。
These are ideal classes to start using if you're looking to get into Lang. StringUtils' capitalize, substringBetween/Before/After, split and join are good methods to begin with. If you use java.sql.Statements a lot, StringEscapeUtils.escapeSql might be of interest.
上面这几个类是你入门Lang包的首选。StringUtils的如下方法:capitalize, substringBetween/Before/After, split和 join都是入门的好方法。 如果你经常使用java.sql.Statement,那么你也许会对StringEscapeUtils.escapeSql非常感兴趣。

In addition to these classes, WordUtils is another String manipulator. It works on Strings at the word level, for example WordUtils.capitalize will capitalize every word in a piece of text. WordUtils also contains methods to wrap text.
除了这几个类之外,WordUtils也是一个很好的String操作类。它在单词的粒度上进行String操作,例如 WordUtils.capitalize可以对一个文章的所有单词进行操作。 WordUtils也包含了文字换行的方法。

Character handling - CharSetUtils, CharSet, CharRange, CharUtils
In addition to dealing with Strings, it's also important to deal with chars and Characters. CharUtils exists for this purpose, while CharSetUtils exists for set-manipulation of Strings. Be careful, although CharSetUtils takes an argument of type String, it is only as a set of characters. For example, CharSetUtils.delete("testtest", "tr") will remove all t's and all r's from the String, not just the String "tr".
作为对处理String的补充, 处理字符和字母也是重要的部分。 CharUtils就是为该目的而产生。CharSetUtils是对一组字符进行操作。请注意,虽然CharSetUtils的某些方法包含了字符串类型的参数,但它仅仅是把这个字符串看成多个字符。例如,CharSetUtils.delete("testtest", "tr") 会从"testtest"中删掉所有't', 和所有'r',而不是删掉'tr'。
CharRange and CharSet are both used internally by CharSetUtils, and will probaby rarely be used.
CharRange和 CharSet是被 CharSetUtils所调用的,基本没有直接使用它们的情况。
JVM interaction - SystemUtils, CharEncoding
SystemUtils is a simple little class which makes it easy to find out information about which platform you are on. For some, this is a necessary evil. It was never something I expected to use myself until I was trying to ensure that Commons Lang itself compiled under JDK 1.2. Having pushed out a few JDK 1.3 bits that had slipped in (Collections.EMPTY_MAP is a classic offender), I then found that one of the Unit Tests was dying mysteriously under JDK 1.2, but ran fine under JDK 1.3. There was no obvious solution and I needed to move onwards, so the simple solution was to wrap that particular test in a if(SystemUtils.isJavaVersionAtLeast(1.3f)) {, make a note and move on.
SystemUtils是一个小巧简单的类,可以判断出我们使用的java平台的信息。有时,对这个进行判断是不可避免的。我以前从来没想到过会有这个需求,直到某天我需要判定COMMONS-LANG包必须得在JDK1。2下编译。事情是这样的:某天我将几个JDK1.3 的字节进行操作时(译注:原文是:把几个JDK1。3的字节推出一个集合中),发现一个单元测试在JDK1。3下工作正常,但是在JDK1。2下却会很诡异的死掉。没有明确的解决办法,我自己也在摸索。所以使用了目前的解决办法:先进行判断:if(SystemUtils.isJavaVersionAtLeast(1.3f)) {, 然后再继续运行测试代码。

The CharEncoding class is also used to interact with the Java environment and may be used to see which character encodings are supported in a particular environment.
CharEncoding类也被用在了某些交互环境中。可以检查某个字符编码是否被当前环境所支持。
Serialization - SerializationUtils, SerializationException
Serialization doesn't have to be that hard! A simple util class can take away the pain, plus it provides a method to clone an object by unserializing and reserializing, an old Java trick.
串行化并不是想象中的那么难!只要你使用一个简单的工具类就可以很舒服的通过并行化或串行化来COPY一个对象。
Assorted functions - ObjectUtils, ClassUtils, ArrayUtils, BooleanUtils
其他的东东 -
Would you believe it, ObjectUtils contains handy functions for Objects, mainly null-safe implementations of the methods on java.lang.Object.
你信不,OjectUtils包含了对Object的各种操作,主要是null-safe的实现。
ClassUtils is largely a set of helper methods for reflection. Of special note are the comparators hidden away in ClassUtils, useful for sorting Class and Package objects by name; however they merely sort alphabetically and don't understand the common habit of sorting java and javax first.
ClassUtils主要提供了对于反射的一组方法。 Of special note are the comparators hidden away in ClassUtils, 在对Class和Package对象进行排序时非常有用;然而它们仅仅会按字母排序,而且不会把java和javax包放在最前。

Next up, ArrayUtils. This is a big one with many methods and many overloads of these methods so it is probably worth an in depth look here. Before we begin, assume that every method mentioned is overloaded for all the primitives and for Object. Also, the short-hand 'xxx' implies a generic primitive type, but usually also includes Object.
下一个出场的是ArrayUtils. 这个大家伙包含了多个一般方法以及多个重载的方法,因此对它的介绍我们一定要好好的了解下。在开始之前,假设每个方法都被overloaded(重载)了。同样,简写的 'xxx'则代表所实现的对应的类型。
* ArrayUtils provides singleton empty arrays for all the basic types. These will largely be of use in the Collections API with its toArray methods, but also will be of use with methods which want to return an empty array on error.
* ArrayUtils提供了一个singleton的空数组,支持所有基本类型。它不但在使用Collections API 的toArray方法时特别有用,而且也可以用在程序出错时返回空数组。
* add(xxx[], xxx) will add a primitive type to an array, resizing the array as you'd expect. Object is also supported.
* add(xxx[], xxx) 可以向一个数组中增加东东,然后按你所想的那样增加该数组的大小。
* clone(xxx[]) clones a primitive or Object array.
clone一个数组。
* contains(xxx[], xxx) searches for a primitive or Object in a primitive or Object array.
在数组中进行查询一个东东。
* getLength(Object) returns the length of any array or an IllegalArgumentException if the parameter is not an array. hashCode(Object), equals(Object, Object), toString(Object)
getLength(Object)返回一个数组的长度。如果参数中的object不是数组,则抛出IllegalArgumentException .
* indexOf(xxx[], xxx) and indexOf(xxx[], xxx, int) are copies of the classic String methods, but this time for primitive/Object arrays. In addition, a lastIndexOf set of methods exists.
indexOf(xxx[], xxx) and indexOf(xxx[], xxx, int) copy与经典的String方法,只不过它们用在了数组上。另外还有一组 lastIndexOf方法。

* isEmpty(xxx[]) lets you know if an array is zero-sized or null.
isEmpty(xxx[]) 可以让我们了解某个数组是0大小的,还是null.
* isSameLength(xxx[], xxx[]) returns true if the arrays are the same length.
isSameLength(xxx[], xxx[]) 可以比较两个数组的长度, 相同的话返回true.
* Along side the add methods, there are also remove methods of two types. The first type remove the value at an index, remove(xxx[], int), while the second type remove the first value from the array, remove(xxx[], xxx).
除了上面的add方法,还有两种remove方法。一个是移除指定位置的值: remove(xxx[], int) ,另一个是移除第一次出现的值:remove(xxx[], xxx).

* Nearing the end now. The reverse(xxx[]) method turns an array around.
快介绍完了(译注:其实下面还有不少啊!) reverse(xxx[]) 方法会返回一个反转顺序的数组。
* The subarray(xxx[], int, int) method splices an array out of a larger array.
subarray(xxx[],int,int) 可以从一个大数组中摘出一小段。
* Primitive to primitive wrapper conversion is handled by the toObject(xxx[]) and toPrimitive(Xxx[]) methods.
可以使用toObject(xxx[]) 和 toPrimitive(Xxx[]) 对primitive和Object类型进行转换。
Lastly, ArrayUtils.toMap(Object[]) is worthy of special note. It is not a heavily overloaded method for working with arrays, but a simple way to create Maps from literals.
最后,值得我们注意的是:ArrayUtils.toMap(Object[]) 这个方法。它不是对操作数据的method的重量级重载,而是一个简单的建立Map的办法:
Using toMap
用法:

Map colorMap = MapUtils.toMap(new String[][] {{
{"RED", "#FF0000"},
{"GREEN", "#00FF00"},
{"BLUE", "#0000FF"}
});

Our final util class is BooleanUtils. It contains various Boolean acting methods, probably of most interest is the BooleanUtils.toBoolean(String) method which turns various positive/negative Strings into a Boolean object, and not just true/false as with Boolean.valueOf.
我们最后的工具类是 BooleanUtils. 它包含了多种Boolean相关的方法。也许最让你感兴趣的是 BooleanUtils.toBoolean(String),
它可以把 正数/负数 以及String转换成一个Boolean对象,而不必使用Boolean.valueOf.

Exceptions - IllegalClassException, IncompleteArgumentException, NotImplementedException, NullArgumentException, UnhandledException
Lang also has a series of Exceptions that we felt are useful. All of these exceptions are descendents of RuntimeException, they're just a bit more meaningful than java.lang.IllegalArgumentException.
Lang也有一系列有用的异常。这些异常都是RuntimeException的子类,它们只是在名字上比java.lang.IllegalArgumentException更有意义。

Flotsam - BitField, Validate
On reaching the end of our package, we are left with a couple of classes that haven't fit any of the topics so far.
在本package最后,还有几个我们没有说到的类。
The BitField class provides a wrapper class around the classic bitmask integer, whilst the Validate class may be used for assertions (remember, we support Java 1.2).
BitField提供了对经典的bitmask整数的进行了封装的类。而Validate类可以用来断言(我们支持Java1.2)

lang.builder.*
When you write a hashcode, do you check Bloch's Effective Java? No? You just hack in a quick number? Well HashCodeBuilder will save your day. It, and its buddies (EqualsBuilder, CompareToBuilder, ToStringBuilder), take care of the nasty bits while you focus on the important bits, like which fields will go into making up the hashcode.
lang.enums.* (formerly lang.enum)
写某个hashcode方法时,你是否遵照了Bloch的Effective Java? 没有?你只是写了一个常数?恩。。。HashCodeBuilder可以助你一臂之力。它和它的几个兄弟(EqualsBuilder, ComparaToBuilder, ToStringBuilder)可以让你把精力投入到更重要的事情上。

Enums are an old C thing. Very useful. One of the major uses is to give type to your constants, and even more, to give them order. For example:
枚举(Enum)是比较老旧的概念,从C而来。非常好用。一个主要的用法是把常量作为类型,甚至设置他们的顺序,例如:
A simple Enum
public final class ColorEnum extends Enum {
public static final ColorEnum RED = new ColorEnum("Red");
public static final ColorEnum GREEN = new ColorEnum("Green");
public static final ColorEnum BLUE = new ColorEnum("Blue");
private ColorEnum(String color) {
super(color);
}
public static ColorEnum getEnum(String color) {
return (ColorEnum) getEnum(ColorEnum.class, color);
}
public static Iterator iterator() {
return iterator(ColorEnum.class);
}
}
The enums package used to be the enum package, but with Java 5 giving us an enum keyword, the move to the enums package name was necessary and the old enum package was deprecated.
enums包本来是个包,但是Java5给了我们一个enum关键字,所以 原来的enums包现在不建议使用了。
lang.exception.*
JDK 1.4 brought us NestedExceptions, that is an Exception which can link to another Exception. This subpackage provides it to those of us who have to code to something other than JDK 1.4 (most reusable code libaries are aimed at JDK 1.2).
JDK1.4 给我们带来了 NestedException,它可以与其他的Exception进行关联。本包的使用者是没有使用JDK 1。4的用户(而是使用JDK1。2的用户),向他们提供了NestedException 类似的类。

---- 以下也许有敏感词汇???

It isn't just a nested exception framework though, it uses reflection to allow it to handle many nested exception frameworks, including JDK 1.4's.
它不仅仅是一个neste exception框架,它还通过reflection来处理多个nexted exception 框架,包括JDK1。4的。The reflection ability is one of the more interesting tricks hidden in the reflection sub-package, and of much use to writers of applications such as Tomcat or IDEs, in fact any code which has to catch 'Exception' from an unknown source and then wanting to display in a novel way.
reflection是最好玩的编程技巧之一。它隐藏在reflection包中,在例如Tomcat或者IDE这样的应用中大量的被用来输出信息。实际上任何被catch到的unkown source的Exception,都需要用它来显示。
lang.math.*
Although Commons-Math also exists, some basic mathematical functions are contained within Lang. These include classes to represent ranges of numbers, a Fraction class, various utilities for random numbers, and the flagship class, NumberUtils which contains a handful of classic number functions.
尽管Commons-Math已经存在,但是Lang包里还是包含了基本的数学工具,包括了表示数字的范围的,Fraction类,可以产生多种随即数的,以及最核心的类:包含了一组经典的处理数字方法的NumberUtils类。

---- 敏感词汇?

There are two aspects of this package I would like to highlight. The first is NumberUtils.createNumber(String), a method which does its best to convert a String into a Number object. You have no idea what type of Number it will return, so you should call the relevant xxxValue method when you reach the point of needing a number. NumberUtils also has a related isNumber method. The second is the JVMRandom class. This is an instance of Random which relies on the Math.random() method for its implementation and so gives the developer access to the JVM's random seed. If you try to create Random objects in the same millisecond, they will give the same answer; so quickly you will find yourself caching that Random object. Rather than caching your own object, simply use the one the JVM is caching already. The RandomUtils provides a static access to the JVMRandom class, which may be easier to use.
我想说下这个包中的两个突出内容。首先要说的是 NumberUtils.createNumber(String),它可以最大程序的把一个String转换成一个Number对象。它返回的Number类型是不定的,所以我们需要使用对应的xxxValue方法得到最终结果。NumberUtils也有相关的 isNumber方法。第二要说的是 JVMRandom类。它是依靠Math.random()而来的一个Random的实例,使开发人员可以访问JVM的随机seed.如果我们在同样的毫秒内建立同样的Random对象,就会得到同样的结果。所以我们就知道我们已经对Random对象放在了缓存里。请不要这样做,而是使用已经存在JVM缓存中的Random对象。也就是说,RandomUtils提供更易于使用的访问JVMRandom类的静态方法。
lang.mutable.*
New in 2.1, the mutable package provides mutable wrappers for primitive values (such as int, long, etc.) and Object. These wrappers are simiar to the wrappers provided by the Java API, but allow the wrapped value to be changed without needing to create a separate wrapper object.
2.1版新增加的内容。mutable 包提供了对基本类型和Object的一系列的wrapper,它们与Java API所提供的类似,但是允许在不建立另一个封wrapper对象的情况下改变当前wrapper的值。
lang.text.*

---- 敏感词汇?

2.2版新增加的内容。它提供了这些类:可以取代StringBuffer的StrBuilder类,可以在某个String内对变量进行替换的StrSubstitutor类,
以及可以取代StringTokenizer的StrTokenizer类。尽管“Str”作为前缀非常难看,但是这样可以确保不与现在或将来的标准Java类相,冲.突


---- 敏感词汇?

lang.time.*
Lang 2.0 saw the arrival of a time package. It contains some basic utilities for manipulating time (a delorean, police box and grandfather clock?). These include a StopWatch for simple performance measurements and an optimised FastDateFormat class.
Lang2.0版新增内容。包括了操作时间的基本类(a delorean,我差点翻译成机器猫-_-!,police box and grandfather clock?)包括一个进行简单的性能测量的StopWatch类 和 优化了的FastDateFormat类.

New in Lang 2.1 is the DurationFormatUtils class, which provides various methods for formatting durations.
Lang2.1版增加了DurationFormatUtils类,它提供了多种格式化一段时间的方法。

Back