1 22 package org.jboss.reflect.plugins; 23 24 import java.beans.PropertyEditor ; 25 import java.beans.PropertyEditorManager ; 26 import java.lang.reflect.Constructor ; 27 import java.lang.reflect.Method ; 28 import java.lang.reflect.Modifier ; 29 30 import org.jboss.logging.Logger; 31 import org.jboss.reflect.plugins.introspection.ReflectionUtils; 32 import org.jboss.util.propertyeditor.PropertyEditors; 33 34 41 public class ValueConvertor 42 { 43 44 private static final Logger log = Logger.getLogger(ValueConvertor.class); 45 46 static 47 { 48 try 49 { 50 PropertyEditors.init(); 51 } 52 catch (Throwable t) 53 { 54 log.debug("Unable to initialise property editors", t); 55 } 56 } 57 58 67 public static Object convertValue(Class <? extends Object > clazz, Object value) throws Throwable 68 { 69 if (clazz == null) 70 throw new IllegalArgumentException ("Null class"); 71 if (value == null) 72 return null; 73 74 Class <? extends Object > valueClass = value.getClass(); 75 if (clazz.isAssignableFrom(valueClass)) 76 return value; 77 78 if (clazz.isEnum()) 80 { 81 Class <? extends Enum > eclazz = clazz.asSubclass(Enum .class); 82 return Enum.valueOf(eclazz, value.toString()); 83 } 84 85 if (valueClass == String .class) 87 { 88 PropertyEditor editor = PropertyEditorManager.findEditor(clazz); 89 if (editor != null) 90 { 91 editor.setAsText((String ) value); 92 return editor.getValue(); 93 } 94 } 95 96 try 98 { 99 Method method = clazz.getMethod("valueOf", new Class [] { valueClass }); 100 int modifiers = method.getModifiers(); 101 if (Modifier.isPublic(modifiers) && Modifier.isStatic(modifiers) 102 && clazz.isAssignableFrom(method.getReturnType())) 103 return ReflectionUtils.invoke(null, method, new Object [] { value }); 104 } 105 catch (Exception ignored) 106 { 107 } 108 109 110 if (valueClass == String .class) 112 { 113 try 114 { 115 Constructor constructor = clazz.getConstructor(new Class [] { String .class }); 116 if (Modifier.isPublic(constructor.getModifiers())) 117 return ReflectionUtils.newInstance(constructor, new Object [] { value }); 118 } 119 catch (Exception ignored) 120 { 121 } 122 } 123 124 return value; 125 } 126 } 127 | Popular Tags |