如何使Java方法通用?

时间:2013-01-10 09:51:28

标签: java generics methods

我目前正在开发一个项目,我必须使一些方法通用(以使代码更具可读性)。

项目有两个类:BoxMyList。 'Box'的构造函数接受泛型参数; 'MyList'的构造函数只有一个。

public class Box<A, B> {}

这是盒子的类。

public class MyList<T> {}

那就是MyList的类。

在“Box”类中,我有一个如下所示的方法:

public static MyList enclose (Box <MyList <Integer, String>> t) {
// Here comes some code that is not important right now.
}

我现在想要的是使这个方法具有通用性,这样它不仅可以获取像Box这样的参数。有人有想法吗?

3 个答案:

答案 0 :(得分:0)

尝试

public static <T> MyList<T> enclose(T t) {
    return new MyList<T>();
}

public static void main(String[] args) {
    MyList<Box<String, String>> res = enclose(new Box<String, String>());
}

答案 1 :(得分:0)

目前还不完全清楚你想做什么,而且通用参数的数量与你的类不匹配,但这可能会有效吗?

public <T> static MyList<T> enclose (Box <MyList <T>, String> t) {
// Here comes some code that is not important right now.
}

或者如果你想避免谈论MyList,也许这就是:

public <T> static T enclose (Box <T, String> t) {
// Here comes some code that is not important right now.
}

第二个版本具有Box对象的第一个泛型参数的类型作为其返回类型...

答案 2 :(得分:0)

public static <T, S> MyList<T> enclose(Box <MyList<T>, S> box) {}

Java没有higher kinded types,因此上面的内容与java允许的一样通用。

或者,不需要MyList<T>

public static <T, S> T enclose(Box <T, S> box) {}

希望这两个示例能够让您大致了解如何在特定情况下声明泛型。