Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

instanceof, but have a reference to Class

 
Mark Spritzler
ranger
Sheriff
Posts: 17278
6
IntelliJ IDE Mac Spring
  • Mark post as helpful
  • send pies
  • 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
 
Gregg Bolinger
GenRocket Founder
Ranch Hand
Posts: 15302
6
Chrome IntelliJ IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
 
Mark Spritzler
ranger
Sheriff
Posts: 17278
6
IntelliJ IDE Mac Spring
  • Mark post as helpful
  • send pies
  • 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
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic