泛型对象的使用

2024-10-09 11:18:23 浏览数 (1)

泛型对象的使用

代码语言:javascript复制
package com.example.core.mydemo.java;

import java.util.Objects;

/**
 * output:
 * null
 * null
 * java.lang.Object@3b07d329
 * 0
 * java.lang.Object@41629346
 * 0
 * @param <T>
 */
public class ObjectTest<T> {
    public <T> String convertObjToStr(T value) {
        return Objects.isNull(value) ? null : value.toString();
    }

    public String convertObjToStr2(T value) {
        return Objects.isNull(value) ? null : value.toString();
    }

    public static void main(String[] args) {
        System.out.println(new ObjectTest().convertObjToStr(null));
        System.out.println(new ObjectTest().convertObjToStr2(null));

        System.out.println(new ObjectTest().convertObjToStr(new Object()));
        System.out.println(new ObjectTest().convertObjToStr2(new Integer(0)));

        System.out.println(new ObjectTest<Object>().convertObjToStr(new Object()));
        System.out.println(new ObjectTest<Integer>().convertObjToStr2(new Integer(0)));
    }
}

0 人点赞