Search code examples
javareflectiondynamiccastingprimitive

Dynamically casting to primitives in Java


Edit: This has since been solved. Thanks to everyone who helped. Invoking the method after casting the object as the correct wrapper class worked. But String.valueOf() is much, much simpler to achieve the same effect.

Hello--

What I'm trying to do may not even be possible. I've spent a few hours now researching and experimenting with various things, so I figured I'd finally ask around to see if anyone knows if this is even possible.

Is it possible, using reflection, to dynamically cast a wrapper for a primitive of an unknown type as a primitive?

I'm basically trying to create a generic toString function which can handle the conversion of any type of primitive to a string. Such a seemingly simple thing is frustratingly difficult (and I am aware I could just test each type to see if it is of type Wrapper.class and cast it specifically, but at this point I'm just pursuing this out of stubbornness).

The following throws a ClassCastException. The primClass class appears to be the right one (gives "int" when printing primClass.getName()).

    private String toString(Number obj){
    String result = "";
    try{
        Class objClass = obj.getClass();
        Field field = objClass.getDeclaredField("TYPE");
        Class primClass = (Class)field.get(obj);
        Method method = objClass.getMethod("toString", new Class[]{primClass});
        Object args = new Object[]{primClass.cast(obj)};
        result = (String)method.invoke(null, args);
    }catch(Exception ex){
        //Unknown exception. Send to handler.
        handleException(ex);
    }
    return result;
}

So I'm a bit at a loss, really. Anyone have any ideas? Any help would be greatly appreciated.


Solution

  • You might want to have a look at Apache Commons Lang, Especially ToStringBuilder.reflectionToString(). Even if you don't want to introduce a dependency just for a toString(), it's open source so you can have a look at the implementation.

    method.invoke accept the Wrapper types instead of the primivtes types.