1. 程式人生 > >使用XStream序列化、反序列化XML資料時遇到的各種問題

使用XStream序列化、反序列化XML資料時遇到的各種問題

publicclass LevinEnumSingleNameConverter extends EnumSingleValueConverter {
    
privatestaticfinal String CUSTOM_ENUM_NAME_METHOD ="getName";
    
privatestaticfinal String CUSTOM_ENUM_VALUE_OF_METHOD ="toEnum";
   
    
private Class<?extends Enum<?>> enumType;
 
    
public LevinEnumSingleNameConverter(Class
<?extends Enum<?>> type) {
        
super(type);
        
this.enumType = type;
    }
 
    @Override
    
public String toString(Object obj) {
        Method method 
= getCustomEnumNameMethod();
        
if(method ==null) {
            
returnsuper.toString(obj);
        } 
else {
            
try {
                
return (String)method.invoke(obj, (Object[])null);
            } 
catch(Exception ex) {
                
returnsuper.toString(obj);
            }
        }
    }
 
    @Override
    
public Object fromString(String str) {
        Method method 
= getCustomEnumStaticValueOfMethod();
        
if(method ==null) {
            
return enhancedFromString(str);
        }
        
try {
            
return method.invoke(null, str);
        } 
catch(Exception ex) {
            
return enhancedFromString(str);
        }
    }
   
    
private Method getCustomEnumNameMethod() {
        
try {
            
return enumType.getMethod(CUSTOM_ENUM_NAME_METHOD, (Class<?>[])null);
        } 
catch(Exception ex) {
            
returnnull;
        }
    }
   
    
private Method getCustomEnumStaticValueOfMethod() {
        
try {
            Method method 
= enumType.getMethod(CUSTOM_ENUM_VALUE_OF_METHOD, (Class<?>[])null);
            
if(method.getModifiers() == Modifier.STATIC) {
                
return method;
            }
            
returnnull;
        } 
catch(Exception ex) {
            
returnnull;
        }
    }
   
    
private Object enhancedFromString(String str) {
        
try {
            
returnsuper.fromString(str);
        } 
catch(Exception ex) {
            
for(Enum<?> item : enumType.getEnumConstants()) {
                
if(item.name().equalsIgnoreCase(str)) {
                    
return item;
                }
            }
            
thrownew IllegalStateException("Cannot converter <"+ str +"> to enum <"+ enumType +">");
        }
    }
}