• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

question on reflection

 
Raj Sing
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All,

I had a problem during reflecting a method that accepts primitive aruguments.

I had a handler class called GenericValidator that has a method called

isInRange(int,int,int).


My program parses an xml file and gets handler class, methodName and all the arguments as Strings.

And the invoke method works only if I convert all the arguments to its respective wrapper Objects.

But for converting the primitives to their respective Wrapper Objects,
I had to write a method like one below (Though I didnt like write such a method).

Is there a better way of converting a String to an appropriate WrapperObject based on its value??


private static Object getWrapperObject(String primitive,String value){

Object wrapperObject = null;

if(primitive.equalsIgnoreCase("int")){

wrapperObject = new Integer(value);
}
else if(primitive.equalsIgnoreCase("float")){
wrapperObject = new Float(value);
}
else if(primitive.equalsIgnoreCase("double")){
wrapperObject = new Double(value);
}
else if(primitive.equalsIgnoreCase("long")){
wrapperObject = new Long(value);
}
else if(primitive.equalsIgnoreCase("short")){
wrapperObject = new Short(value);
}
else if(primitive.equalsIgnoreCase("byte")){
wrapperObject = new Byte(value);
}
else if(primitive.equalsIgnoreCase("char")){
wrapperObject = new Character (value.toCharArray()[0]);
}

return wrapperObject;
}
 
Maulin Vasavada
Ranch Hand
Posts: 1873
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Raj,

I guess you would have to do it the way you are doing because you are getting argument values as "String" not in primitive type as int and all.

In reflection, if the method has primitive type as argument you would have to pass appropriate wrapper object.

Thanks
Maulin
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm fanatical about reducing or removing long if/else statements like that. Most of the wrapper classes can be created with a single String argument. I made a generic wrapper creator that looks up the primitive type in a hashmap, gets the wrapper Class and uses reflection to invoke the single String constructor on the wrapper. Worked for all but Character which took a special case.

Coming into this mValue is always a String. Coming out, it is an instance of hte proper wrapper. The Reflector just finds the matching constructor and invokes it. This code is here if you care: http://www.surfscranton.com/architecture/Interpreter.htm
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic