Reputation: 12377
String s = "abc";
Integer i = 123;
System.out.println (s.getClass().getTypeName());
System.out.println (i.getClass().getTypeName());
Output is
java.lang.String
java.lang.Integer
I'd like to have some smaller type-identification (like a unique number). I need to store it and therefore I would prefer in a shorter way.
Upvotes: 0
Views: 204
Reputation: 12377
Think the proposed solutions in the comments with getSimpleName (RedCam) and hashCode of the Class (Ricky Mo, kutschkern) are the best for my requirements. Thanks!
String s = "abc";
String ss = "abcd";
Integer i = 123;
Integer ii = 1234;
System.out.println (s.getClass().getSimpleName() + " " + s.getClass().hashCode());
System.out.println (ss.getClass().getSimpleName() + " " + ss.getClass().hashCode());
System.out.println (i.getClass().getSimpleName() + " " + i.getClass().hashCode());
System.out.println (ii.getClass().getSimpleName() + " " + ii.getClass().hashCode());
Output
String 349885916
String 349885916
Integer 1627674070
Integer 1627674070
Upvotes: 1
Reputation: 59410
You can hash the string, like hashCode()
, which is available on any object and it returns an int
. Basically, the int
is a simple number which needs less storage space and has higher performance. However, the calculation of a hash needs some time.
I say "like", because you can't actually use that method. The method is not guaranteed to return the same result for different executions of the application, so you must not store it in a database.
But there are hash functions that guarantee the same result, e.g. simple ones like MD5. (How can I generate an MD5 hash?)
However, note that a hash is a one-way conversion. If, for whatever reason (possible an unknown reason at this point in time), you need the type as the name again, there's no way to do that.
Upvotes: 1
Reputation: 8163
Compress the Strings. The range of characters is not very big, so compression should work pretty well.
GZipInputStream / GZipOutputStream should work well.
There is no numerical ID for classes, just the String. So you have to come up with your own method of assigning IDs.
Upvotes: 0
Reputation: 189
You could use a switch statement to assign a 'tag' you can think of yourself to define them with a shorter 'id':
int id = 0;
switch(s.getClass().getTypeName()) {
case "java.lang.String":
id = 1;
break;
case "java.lang.Integer":
id = 2;
break;
default:
id = 0;
}
Upvotes: 0