It's not a secret anymore!
The moose likes Beginning Java and the fly likes Character.getType()  ? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Character.getType()  ?" Watch "Character.getType()  ?" New topic

Character.getType() ?

bob connolly
Ranch Hand

Joined: Mar 10, 2004
Posts: 204
Hello, when i use the Character.getType(_) method, it returns an int value, i'm wondering how to convert that int value, ie the 15 below, to a meaningfull literal like "CONTROL" or "isaCONTROL" character or something like that!

Thanks very much!

t 9 15 <<<<<
n 10 15
r 13 15
f 12 15
Philip Heller
Ranch Hand

Joined: Oct 24, 2000
Posts: 119
Great question, Bob!

There's no good way to do it. As you've seen from the API page, Character has a bunch of static constants. How do you translate a number to a name? I guess you could do this:

But it seems wrong. Below is a way to do it using reflection. The code scans all field names in java.lang.Character, looking for the first byte that matches the getType() of the char. As a general approach that's 99% good enough in my experience, but your actual mileage may vary. It's still cheesy.

I can't think of a better approach, and the moral is: use enums where possible. If the char types were enums rather than bytes, toString() would automatically return the enum's name, which would be exactly what you want.

Here's the reflection code.


Consultant to SCJP team.<br />Co-designer of SCJD exam.<br />Co-author of "Complete Java 2 Certification Study Guide".<br />Author of "Ground-Up Java".
bob connolly
Ranch Hand

Joined: Mar 10, 2004
Posts: 204
Much Thanks Philip!

Have lots to study here, really appreicate the suggestions!

Have a great week!

I agree. Here's the link:
subject: Character.getType() ?
jQuery in Action, 3rd edition