问题
Can somebody suggest any approach to generate unique Id preferably integer for Java classes .I need to have each of my Java classes to have some kind of a unique Id which would be written via a serialization strategy to be used to get back the same class in a distributed set up .
回答1:
Take a look at the UUID class. It has toString() function. You could take the hash of that value.
回答2:
While not an integer, another way is to use SecureRandom:
new BigInteger(130, new SecureRandom()).toString(32)
returns a String that looks something like "61iook8njttgnmp06aku56gmtc"
Note that if at all possible it would be better to create a single SecureRandom and reuse it when generating your unique id.
Edit: sorry, can't comment yet but I see that you added a comment to the UUID answer - also an excellent way to solve the original problem you stated. However, now you want a "unique key" for your object. You really need to come up with a correct hashCode() method for your object. You need to answer what separates one version of your object from the other - a string perhaps that you could call hashCode() on?
回答3:
I'n mot sure you can get what you want.
It would be nice to have the entire thing be an automated part of the build process so it sort of "just happens".
It seems the only near constant information available from a Java class to represent a unique class is the full package and class name "canonical path". But if someone renames it or changes the package you are screwed.
To get any shorter ID that is assigned once and persistent will require some sort of persistent registry database loaded at application startup and available to all applications that will be serializing the same classes. You then then look up the actual runtime class from it and assign it to an internal registry.
It would be nice if in some manner by which a unique ID can be generated when a class without an assigned ID is first created, and an annotation or other field can be added to the source code for the classes in question.
来源:https://stackoverflow.com/questions/32639692/generating-unique-int-id-for-my-java-classes-used-as-cache-keys