uuidgenerator.java

来自「Struts2 + Spring JPA Hibernate demo.」· Java 代码 · 共 57 行

JAVA
57
字号
package com.vegeta.utils.idgen;

import com.vegeta.utils.MathUtil;
import com.vegeta.utils.format.Format;

/**
 * Several UUID generators. Which one to use depends on destiantion evironemnt.
 * Generated UUIDs are not sequencial.
 * 
 * <p>
 * <a href="UuidGenerator.java.html"><i>View Source</i></a>
 * </p>
 * 
 * @version $Revision: 41 $ $Date: 2006-06-27 23:17:14 +0800 (星期二, 27
 *          六月 2006) $
 */
public class UuidGenerator {

	private final static String chars64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

	/**
	 * Returns unique String of 16 chars. This string is based on following
	 * template: 32bits from current time, 32bits from identityHashCode 32bits
	 * from random Total 96 bits, that are coded with base 6 so resulting string
	 * will have just 16 chars.
	 * 
	 * @param o
	 * 
	 * @return uuid as string of 16 chars
	 */
	public final static String generate(Object o) {
		long id1 = System.currentTimeMillis() & 0xFFFFFFFFL;
		long id2 = System.identityHashCode(o);
		long id3 = MathUtil.randomLong(-0x80000000L, 0x80000000L) & 0xFFFFFFFFL;

		id1 <<= 16;
		id1 += (id2 & 0xFFFF0000L) >> 16;
		id3 += (id2 & 0x0000FFFFL) << 32;

		return Format.convert(id1, 6, chars64) + Format.convert(id3, 6, chars64);
	}

	/**
	 * Returns just 10 random chars. Just based on current time and a random
	 * string.
	 * 
	 * @return uuid string of 10 chars
	 * @see #generate(Object o)
	 */
	public final static String generate() {
		long id1 = System.currentTimeMillis() & 0x3FFFFFFFL;
		long id3 = MathUtil.randomLong(-0x80000000L, 0x80000000L) & 0x3FFFFFFFL;

		return Format.convert(id1, 6, chars64) + Format.convert(id3, 6, chars64);
	}
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?