1 16 package org.apache.cocoon.woody.datatype.convertor; 17 18 import java.lang.reflect.Field ; 19 import java.lang.reflect.Method ; 20 import java.lang.reflect.Modifier ; 21 import java.util.Locale ; 22 23 import org.apache.avalon.framework.CascadingRuntimeException; 24 25 34 public class EnumConvertor implements Convertor { 35 36 private Class clazz; 37 38 43 public EnumConvertor(String className) { 44 try { 45 clazz = Class.forName(className); 46 } 47 catch (ClassNotFoundException e) { 48 throw new CascadingRuntimeException("Class " + className + " not found", e); 49 } 50 } 51 52 55 public Object convertFromString(String value, 56 Locale locale, 57 FormatCache formatCache) { 58 try { 59 try { 61 Method method = getTypeClass(). 62 getMethod("fromString", new Class [] { String .class, Locale .class}); 63 return method.invoke(null, new Object [] { value, locale}); 64 } catch(NoSuchMethodException nsme) { 65 int pos = value.lastIndexOf('.'); 69 if (pos >= 0) { 70 value = value.substring(pos + 1); 71 } 72 Class clazz = getTypeClass(); 73 Field field = clazz.getField(value); 74 return field.get(null); 75 } 76 } catch (Exception e) { 77 throw new CascadingRuntimeException("Got exception trying to convert " + value, e); 78 } 79 } 80 81 84 public String convertToString(Object value, 85 Locale locale, 86 FormatCache formatCache) { 87 Class clazz = getTypeClass(); 88 Field fields[] = clazz.getDeclaredFields(); 89 for (int i = 0 ; i < fields.length ; ++i) { 90 try { 91 int mods = fields[i].getModifiers(); 92 if (Modifier.isPublic(mods) 93 && Modifier.isStatic(mods) 94 && Modifier.isFinal(mods) 95 && fields[i].get(null).equals(value)) { 96 return clazz.getName() + "." + fields[i].getName(); 97 } 98 } catch (Exception e) { 99 throw new CascadingRuntimeException("Got exception trying to get value of field " + fields[i], e); 100 } 101 } 102 return value.toString(); 104 } 105 106 109 public Class getTypeClass() { 110 return clazz; 111 } 112 } 113 | Popular Tags |