0
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.

chris01
  • 10,921
  • 9
  • 54
  • 93

4 Answers4

1

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.

Thomas Weller
  • 55,411
  • 20
  • 125
  • 222
  • But that would be one-way and render the stored data pretty useless as there would be no way (except brute force) to retrieve the classes from the hashes. – Nicktar Dec 06 '19 at 07:44
1

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
chris01
  • 10,921
  • 9
  • 54
  • 93
0

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;
}
Quadrivics
  • 181
  • 2
  • 10
0

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.

kutschkem
  • 7,826
  • 3
  • 21
  • 56