91超碰碰碰碰久久久久久综合_超碰av人澡人澡人澡人澡人掠_国产黄大片在线观看画质优化_txt小说免费全本

溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

XStream的使用

發布時間:2020-07-19 00:19:05 來源:網絡 閱讀:1349 作者:mybabe0312 欄目:軟件技術

本文主要用于記錄XStream的使用方式,特別是其中的“對象默認值”和Map轉換器的使用

1,添加Maven依賴

<dependency>
          <groupId>com.thoughtworks.xstream</groupId>
          <artifactId>xstream</artifactId>
          <version>1.4.11.1</version>
</dependency>

2,創建可以使用默認值的對象

import java.lang.reflect.Field;

import com.thoughtworks.xstream.converters.reflection.ObjectAccessException;
import com.thoughtworks.xstream.converters.reflection.PureJavaReflectionProvider;

public class FieldDefaultValueProvider extends PureJavaReflectionProvider {

    /**
     * @param object 目標類的實例
     * @param fieldName XML中顯示指明的字段
     * @param definedIn 父類或者類本身
     */
    @Override  
    public void writeField(Object object, String fieldName, Object value, Class definedIn) {
        Field field = fieldDictionary.field(object.getClass(), fieldName, definedIn);//返回存在于xml中的字段  
        validateFieldAccess(field);//驗證字段可以被訪問 
        try {  
            if (value instanceof String) {
                String trim = ((String)value).trim();//字符串首尾去空
                if(trim.length()==0)//如果是空字符串,則不做賦值,使用默認初始值
                    return;
                field.set(object,trim);  
            }else{
                field.set(object, value);  
            }
        } catch (IllegalArgumentException e) {  
            throw new ObjectAccessException("Could not set field " + object.getClass() + "." + field.getName(), e);  
        } catch (IllegalAccessException e) {  
            throw new ObjectAccessException("Could not set field " + object.getClass() + "." + field.getName(), e);  
        }  
    }  
}

3,創建用于轉換Map的對象

import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

import com.thoughtworks.xstream.converters.MarshallingContext;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.converters.collections.AbstractCollectionConverter;
import com.thoughtworks.xstream.io.ExtendedHierarchicalStreamWriterHelper;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
import com.thoughtworks.xstream.mapper.Mapper;

public class MapCustomConverter extends AbstractCollectionConverter {

    public MapCustomConverter(Mapper mapper) {
        super(mapper);
    }

    @Override
    public boolean canConvert(Class type) {
        return type.equals(HashMap.class) || type.equals(Hashtable.class)
                || type.getName().equals("java.util.LinkedHashMap") || type.getName().equals("sun.font.AttributeMap");
    }

    @Override
    public void marshal(Object source, HierarchicalStreamWriter writer, MarshallingContext context) {
        Map map = (Map) source;
        for (Iterator iterator = map.entrySet().iterator(); iterator.hasNext();) {
            Entry entry = (Entry) iterator.next();
            ExtendedHierarchicalStreamWriterHelper.startNode(writer, "property", Entry.class);

            writer.addAttribute("key", entry.getKey().toString());
            writer.addAttribute("value", entry.getValue().toString());
            writer.endNode();
        }
    }

    @Override
    public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {
        Map map = (Map) createCollection(context.getRequiredType());
        populateMap(reader, context, map);
        return map;
    }

    protected void populateMap(HierarchicalStreamReader reader, UnmarshallingContext context, Map map) {
        while (reader.hasMoreChildren()) {
            reader.moveDown();
            Object key = reader.getAttribute("key");
            Object value = reader.getAttribute("value");
            map.put(key, value);
            reader.moveUp();
        }
    }
}

4,創建XStream對象

private static XStream getXStream() {
        // XStream xstream = new XStream();//需要XPP3庫
        // XStream xstream = new XStream(new DomDriver());// 不需要XPP3庫
        //  XStream xstream = new XStream(new StaxDriver());// 不需要XPP3庫開始使用Java6

        XStream xstream = new XStream(new FieldDefaultValueProvider(),new DomDriver());// 創建Xstram對象
        xstream.autodetectAnnotations(true);
        xstream.addPermission(AnyTypePermission.ANY);
        xstream.registerConverter(
                new MapCustomConverter(new DefaultMapper(new ClassLoaderReference(XStream.class.getClassLoader()))));
        XStream.setupDefaultSecurity(xstream);
        xstream.allowTypes(new Class[] { CollectTaskMeta.class, FtpConfig.class, TaskParallel.class,
                TaskRootConfig.class, Sql.class });
        xstream.processAnnotations(new Class[] { CollectTaskMeta.class, FtpConfig.class, TaskParallel.class,
                TaskRootConfig.class, Sql.class });
        return xstream;
    }

5,使用XStream來解析文件

import org.springframework.util.ResourceUtils;

XStream xstream = getXStream();
TaskRootConfig meteInfo = null;
try {
    meteInfo = (TaskRootConfig) xstream.fromXML(ResourceUtils.getFile("classpath:taskconfig.xml"));
} catch (FileNotFoundException e) {
    e.printStackTrace();
}
向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

道孚县| 新建县| 乌海市| 仪陇县| 裕民县| 杨浦区| 吕梁市| 长治县| 兴安盟| 康乐县| 蚌埠市| 勐海县| 大悟县| 绿春县| 开鲁县| 顺昌县| 西充县| 蓝田县| 昌黎县| 濮阳县| 云浮市| 攀枝花市| 彭阳县| 苏尼特右旗| 鄂托克旗| 黎城县| 黑龙江省| 高邮市| 呼伦贝尔市| 宁津县| 松江区| 保德县| 陕西省| 鲁山县| 日照市| 宁城县| 波密县| 柘荣县| 永登县| 定西市| 汪清县|