aspose file tools*
The moose likes Java in General and the fly likes Clean way of checking if object type is primitive or String Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Clean way of checking if object type is primitive or String" Watch "Clean way of checking if object type is primitive or String" New topic
Author

Clean way of checking if object type is primitive or String

Jay Olsen
Greenhorn

Joined: Jan 26, 2008
Posts: 10
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

Joined: Jul 08, 2003
Posts: 24187
    
  34

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.


[Jess in Action][AskingGoodQuestions]
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18977
    
  40

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


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24187
    
  34

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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Clean way of checking if object type is primitive or String