JAVA 序列化

Posted by yaohong on Thursday, May 28, 2020

TOC

JAVA 序列化

Java编译过程

Java源码-> javac将源码转换成class 文件->java命令执行 class 文件;

方法中的“ T”用途是什么?

在查看别人的源码时,会看到如下的代码:

    public static <T> T readValue(String s, TypeReference<T> ref) throws IOException {
        return objectMapper.readValue(s, ref);
    }

在方法名,前面的<T> T是指什么呢?

一般情况下,Java 语法中,方法前面返回的类型,比如public static int get()中的int就是方法要返回的类型。

同理,public static <T> T readValue返回的是<T> T类型,那<T> T又是啥?

原来<T> T是不指定具体类型,它只是占位符,它可以返回任意类型,其具体类型由其调用者决定。

序列化和反序列化

  • 序列化(也叫串行化,英文:Serialization):表示把对象转成字符串;

  • 反序列化(英文:Deserialization):把字符串转成对象;

如下示例:

Collections Examples
Gson gson = new Gson();
Collection<Integer> ints = Lists.immutableList(1,2,3,4,5);

(Serialization)
String json = gson.toJson(ints); ==> json is [1,2,3,4,5]

(Deserialization)
Type collectionType = new TypeToken<Collection<Integer>>(){}.getType();
Collection<Integer> ints2 = gson.fromJson(json, collectionType);
ints2 is same as ints

「点个赞」

Yaohong

点个赞

使用微信扫描二维码完成支付