代码改变世界

学习apache commons lang3的源代码 (2):RandomStringUtils

2017-11-28 15:03  很大很老实  阅读(1135)  评论(0编辑  收藏  举报

本文,主要是分析类;RandomStringUtils.

下面这个方法的:
count:表示要生成的数量(比如4个字符组成的字符串等)

start,end,表示限定的范围,比如生成ascii码的随机等。

public static String random(int count, int start, int end, final boolean letters, final boolean numbers,
final char[] chars, final Random random) {
if (count == 0) {
return StringUtils.EMPTY;
} else if (count < 0) {
throw new IllegalArgumentException("Requested random string length " + count + " is less than 0.");
}
if (chars != null && chars.length == 0) {
throw new IllegalArgumentException("The chars array must not be empty");
}

if (start == 0 && end == 0) {
if (chars != null) {
end = chars.length;
} else {
if (!letters && !numbers) {
end = Character.MAX_CODE_POINT;
} else {
end = 'z' + 1;
start = ' ';
}
}
} else {
if (end <= start) {
throw new IllegalArgumentException("Parameter end (" + end + ") must be greater than start (" + start + ")");
}
}

final int zero_digit_ascii = 48;
final int first_letter_ascii = 65;

if (chars == null && (numbers && end <= zero_digit_ascii
|| letters && end <= first_letter_ascii)) {
throw new IllegalArgumentException("Parameter end (" + end + ") must be greater then (" + zero_digit_ascii + ") for generating digits " +
"or greater then (" + first_letter_ascii + ") for generating letters.");
}

final StringBuilder builder = new StringBuilder(count);
final int gap = end - start;

while (count-- != 0) {
int codePoint;
if (chars == null) {
codePoint = random.nextInt(gap) + start;

switch (Character.getType(codePoint)) {
case Character.UNASSIGNED:
case Character.PRIVATE_USE:
case Character.SURROGATE:
count++;
continue;
}

} else {
codePoint = chars[random.nextInt(gap) + start];
}

final int numberOfChars = Character.charCount(codePoint);
if (count == 0 && numberOfChars > 1) {
count++;
continue;
}

if (letters && Character.isLetter(codePoint)
|| numbers && Character.isDigit(codePoint)
|| !letters && !numbers) {
builder.appendCodePoint(codePoint);

if (numberOfChars == 2) {
count--;
}

} else {
count++;
}
}
return builder.toString();
}

 

这是其最重要的一个方法。

 

举例如下;

String r = RandomStringUtils.random(5);
System.out.println(r);
// 使用指定的字符生成5位长度的随机字符串
r = RandomStringUtils.random(5, new char[] { 'a', 'b', 'c', 'd', 'e','f', '1', '2', '3' });
System.out.println(r);
// 生成指定长度的字母和数字的随机组合字符串
r = RandomStringUtils.randomAlphanumeric(5);System.out.println(r);
// 生成随机数字字符串
r = RandomStringUtils.randomNumeric(5);System.out.println(r);
// 生成随机[a-z]字符串,包含大小写
r = RandomStringUtils.randomAlphabetic(5);System.out.println(r);
// 生成从ASCII 32到126组成的随机字符串
r = RandomStringUtils.randomAscii(4);System.out.println(r);