KnowledgeHub
Questions
Tags
Users
Search
Alex Rivera
|
Logout
Edit Question
Title
Body
I have a java.lang.reflect.InvocationHandler and I need to implement the method invoke() I have a value of type java.lang.String from my elaboration and I need to convert this value to the appropriate returnType expected by the method (it can be a primitive like int, boolean, double or wrapper classes like Boolean, Integer, Double, Float, etc). Example: public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { String computedValue = compute(...); return convert(method.getReturnType(), computedValue); } private Object convert(Class<?> returnType, String stringValue) { return ...; // what's the simplest way? } I am not expecting to simply implement an automatic conversion between complex objects, but I expect a simple way to convert from String to the standard java types. I've seen (too) many times stuff like this, but it doesn't seem appropriate to me: public static Object toObject( Class clazz, String value ) { if( Boolean.class.isAssignableFrom( clazz ) ) return Boolean.parseBoolean( value ); if( Byte.class.isAssignableFrom( clazz ) ) return Byte.parseByte( value ); if( Short.class.isAssignableFrom( clazz ) ) return Short.parseShort( value ); if( Integer.class.isAssignableFrom( clazz ) ) return Integer.parseInteger( value ); if( Long.class.isAssignableFrom( clazz ) ) return Long.parseLong( value ); if( Float.class.isAssignableFrom( clazz ) ) return Float.parseFloat( value ); if( Double.class.isAssignableFrom( clazz ) ) return Double.parseDouble( value ); return value; } and the above is not even the worse one I saw, so far :) Does anybody have a secret trick here?
Tags (comma-separated)
Save Edits
Cancel