Java 泛型:泛型类


#Java 反射、泛型与注解


简介

什么是泛型类?

泛型变量,在类定义时声明。

示例

package com.example;

import java.io.Serializable;

public class Request<T> implements Serializable {

    private Long timestamp;
    private T data;

    public Long getTimestamp() {
        return timestamp;
    }

    public void setTimestamp(Long timestamp) {
        this.timestamp = timestamp;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }

    @Override
    public String toString() {
        return "Request{" +
                "timestamp=" + timestamp +
                ", data=" + data +
                '}';
    }

}

测试:

package com.example;

public class TestGeneric {

    public static void main(String[] args) {
        Request<String> req = new Request<>();
        req.setTimestamp(1500000000L);
        req.setData("Hello World");
        System.out.println( req.toString() );
    }
}

执行结果:

Request{timestamp=1500000000, data=Hello World}


( 本文完 )