wood burning stoves 2.0*
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 Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Languages » Groovy
Bookmark "instanceof, but have a reference to Class" Watch "instanceof, but have a reference to Class" New topic
Author

instanceof, but have a reference to Class

Mark Spritzler
ranger
Sheriff

Joined: Feb 05, 2001
Posts: 17249
    
    6

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?

Thanks

Mark


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
    
    6



GenRocket - Experts at Building Test Data
Mark Spritzler
ranger
Sheriff

Joined: Feb 05, 2001
Posts: 17249
    
    6

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.

Mark
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: instanceof, but have a reference to Class
 
Similar Threads
Downward casting
When to extend and when to create object
Clean way of checking if object type is primitive or String
How to check the two objects are same?
Urgent help!!!!!!!! java.io.Stream Corrupted Exception: Type code out of range, is 2