Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
The moose likes Groovy and the fly likes instanceof, but have a reference to Class Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Languages » Groovy
Bookmark "instanceof, but have a reference to Class" Watch "instanceof, but have a reference to Class" New topic

instanceof, but have a reference to Class

Mark Spritzler

Joined: Feb 05, 2001
Posts: 17249

OK, so I am creating a validation framework for my project and one of the validation that I want to do is to check to make sure a value is a particular object type.

So in code you typically do

if (myValue instanceof String) or (myValue instanceof Long)

But I can't put in "String" "Long" because well I would have a huge list of if for every single possible type in the world.

But what I do have is a reference to the Class of the type, because that is passed into my method signature.

def validate(fieldValue, Class classType)

as an example, I don't actually have classType typed with "Class" more like def validate(fieldValue, classType)

so now I want to do an instanceof between fieldValue and classType.

so say fieldValue is a String and classType if Class<String>

doing (myValue instanceof classType) will not work as they are different types. One is a String the other Class.

So what am I stupidly missing here?



Perfect World Programming, LLC - Two Laptop Bag - Tube Organizer
How to Ask Questions the Smart Way FAQ
Gregg Bolinger
GenRocket Founder
Ranch Hand

Joined: Jul 11, 2001
Posts: 15299

GenRocket - Experts at Building Test Data
Mark Spritzler

Joined: Feb 05, 2001
Posts: 17249

I ended up with this, which is close to what you posted

I used equals() instead of ==, but in Groovy same thing.

Also I think in my original attempt I needed another pair of parenthesis after the "!". That "!" can be very finicky in Groovy.

Don't get me started about those stupid light bulbs.
subject: instanceof, but have a reference to Class
Similar Threads
How to check the two objects are same?
Clean way of checking if object type is primitive or String
Urgent help!!!!!!!! Corrupted Exception: Type code out of range, is 2
Downward casting
When to extend and when to create object