亚洲激情专区-91九色丨porny丨老师-久久久久久久女国产乱让韩-国产精品午夜小视频观看

溫馨提示×

溫馨提示×

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

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

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

吴旗县| 固始县| 肥乡县| 都江堰市| 南雄市| 嘉义市| 达日县| 安徽省| 隆昌县| 德江县| 贞丰县| 岑巩县| 佛冈县| 诏安县| 赣州市| 沽源县| 湄潭县| 宁阳县| 磐石市| 比如县| 金乡县| 长汀县| 苗栗县| 电白县| 新营市| 隆尧县| 廉江市| 克拉玛依市| 蓝山县| 阿拉尔市| 诸城市| 营山县| 健康| 沁源县| 安陆市| 监利县| 泸州市| 贺州市| 湘乡市| 远安县| 瑞金市|