This week's book giveaway is in the Cloud/Virtualizaton forum.
We're giving away four copies of Mesos in Action and have Roger Ignazio on-line!
See this thread for details.
Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Clean way of checking if object type is primitive or String

 
Jay Olsen
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I'm just wondering if any method exists in Java where I can pass a value of type object and it will check to see if the type is primitive or String. Basically I want to avoid other objects such as collections, reference objects etc. Currently I have the following code




which will only use the value if it is a String or primitive. However, I also have to check if the value is null because a String could be null etc. This is not ideal.

Does anyone know of a method/utility class which could be used to check if the type of the object is of String or primitive. E.g. something like the following

Thanks
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24211
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Integer, Float, Character, etc are not primitives; they are wrapper classes which serve as containers for primitives. They are reference objects. True primitives are types like int, float, double, long, byte, char, and boolean -- non-object types. There's a big difference, since

value instanceof Float

won't even compile if "value" is a primitive. "String" is also not a primitive -- it's a type of object. 'null' is also not a primitive -- it's a literal value.

In any case, I don't believe there's a method any place in the standard API which does quite what you want here. I'd put the code you show below into a static utility method and call it as needed.

 
Henry Wong
author
Marshal
Pie
Posts: 21117
78
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well, you can shorten the check a bit, by checking if it is an instance of Number -- since Byte, Short, Integer, Long, Float, and Double objects are all Number objects.

And BTW, these are wrapper objects. These are not primatives.

Henry
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24211
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Henry Wong wrote:Well, you can shorten the check a bit, by checking if it is an instance of Number -- since Byte, Short, Integer, Long, Float, and Double objects are all Number objects.


I thought about mentioning this, but note that BigInteger and BigDecimal also subclass Numbers, so this check would be a little too permissive.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic