3

I'm trying to build a more-typesafe alternative to base Java reflection, and have run up against a bit of a problem. I've got a class BoundMethod<T> that binds a method and an object so the method can be invoked and the result (of type T) returned in a typesafe manner. This involves passing a Class to the constructor, and using that class to cast the return value (i.e. return returnType.cast(method.invoke(object, params))).

The problem I have is that if I create these objects automatically based on the results of getReturnType() in the method object and the return type is a primitive object, I get a ClassCastException, because you can't dynamically cast to a primitive type. I need a way of substituting the appropriate reference type, but I can't find an easy way of doing this.

Is there some prebuilt solution, or do I need to build one myself?

Jules
  • 14,841
  • 9
  • 83
  • 130
  • 1
    You have to map all the primitive types to their wrappers. e.g. with a `Map` The Refection Library only uses wrappers in any case. – Peter Lawrey Sep 16 '12 at 09:29

1 Answers1

3

Check returnType and see if it is a primitive:

returnType.isPrimitive();

And if it is, get its wrapper class.

Unfortunately, this opens you up to auto-boxing of values, but that's simply what happens when you mix generics and primitives.

Community
  • 1
  • 1
Brian
  • 17,079
  • 6
  • 43
  • 66