java—使方法参数成为泛型或通配符

blpfk2vs  于 2021-07-09  发布在  Java
关注(0)|答案(5)|浏览(285)

我有以下方法

private void test(String A, String B, <?> C) throws Exception {
       //.....
    }

我希望c是一个泛型参数或任何东西(int、long、double等)。正确的方法是什么?

5sxhfpxr

5sxhfpxr1#

使用泛型 Object ```
private void test(String A, String B, Object C) throws Exception {
//.....
}

Something.test("A", "B", C);

5f0d552i

5f0d552i2#

可以同时使用泛型方法和通配符。下面是collections.copy()的方法:

class Collections {
    public static <T> void copy(List<T> dest, List<? extends T> src) {
    ...
}

有关泛型方法的大量资源可在此处找到:http://docs.oracle.com/javase/tutorial/extra/generics/methods.html
回到你的代码。。。

public <T> void test(T o)
{
   ...
}
iih3973s

iih3973s3#

您不应该为该任务使用泛型。通过为不同的基元类型重载该方法,将它们分开处理会更有意义:

private void test(String A, String B, int C) throws Exception { }
private void test(String A, String B, long C) throws Exception { }
private void test(String A, String B, float C) throws Exception { }
7vux5j2d

7vux5j2d4#

首先,不要将变量命名为大写字母。第二,像这样-

private <TYPE> void test(String a, String b, TYPE c) throws Exception {
   //.....
   // c is of the generic type TYPE.
}

使用的任何基元类型都将自动装箱到其对象 Package 器类型(例如,double将是double等)。

sg2wtvxw

sg2wtvxw5#

这样地

private <T> void test(String A, String B, T C) throws Exception {
   //.....
}

相关问题