• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

instanceof, but have a reference to Class

 
ranger
Posts: 17347
11
Mac IntelliJ IDE Spring
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
 
Ranch Hand
Posts: 15304
6
Mac OS X IntelliJ IDE Chrome
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
 
Mark Spritzler
ranger
Posts: 17347
11
Mac IntelliJ IDE Spring
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic