2013-01-10 26 views
1

我目前正在一个项目中,我必须使一些方法通用(使代码更具可读性)。我怎样才能使Java方法通用?

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

public class Box<A, B> {} 

这是箱子的类。

public class MyList<T> {} 

而这就是MyList的类。

在类的“盒子”我有一个看起来像这样的方法:

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

我现在想什么,是让这个方法通用的,因此,它不仅像一个Box参数需要。有没有人有想法?

+0

在Google上搜索真的很难吗? - > http://docs.oracle.com/javase/tutorial/extra/generics/methods.html – x4rf41

+0

我不认为你可以用一种有意义的方式来做到这一点,除非你有一个共同的接口,你想支持的所有类这里。 – Thilo

+0

还是你问如何防止硬编码的“”? – Thilo

回答

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对象作为它的返回类型的第一个通用参数的类型...

+0

会尝试! – user1420042

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>()); 
} 
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) {} 

的要求,希望这些2个例子给你如何在特定的情况下,仿制药申报一个粗略的想法。