通用泛型 smaple - w19900227/java-note Wiki

Original URL: https://github.com/w19900227/java-note/wiki/通用泛型-smaple

static <T> void methodName(T val)

class DemoTest {

    @Test
    void test() {
        DemoTest.demo("2");
        DemoTest.demo(2);
        /*
        print
            string - 2
            int - 2
        */
    }

    public static <T> void demo(T val) {
        if (val instanceof String)
            System.out.println("string - " + val);
        if (val instanceof Integer)
            System.out.println("int - " + val);
    }
}

static <T> T methodName(T val)

class DemoTest {

    @Test
    void test() {
        String demo1 = DemoTest.demo("2");
        Integer demo2 = DemoTest.demo(2);
    }

    public static <T> T demo(T val) {
        if (val instanceof String)
            return val;
        if (val instanceof Integer)
            return val;
        return val;
    }
}