我是新来的泛型。这是我的课程。如何从java中的方法返回泛型类型
public interface Animal {
void eat();
}
public class Dog implements Animal {
public void eat() {
System.out.println("Dog eats biscuits");
}
}
public class Cat implements Animal {
public void eat() {
System.out.println("Cat drinks milk");
}
}
现在我想要这些类以通用的方式使用。
public class GenericExample {
public <T extends Animal> T method1() {
//I want to return anything that extends Animal from this method
//using generics, how can I do that
}
public <T extends Animal> T method2(T animal) {
//I want to return anything that extends Animal from this method
//using generics, how can I do that
}
public static void main(String[] args) {
Dog dog = method1(); //Returns a Dog
Cat cat = method2(new Cat()); //Returns a Cat
}
}
如何从方法“method1”和“method2”返回泛型类型(可能是Cat或Dog)。我有几个这样的方法返回“T extends Animal”,所以最好在方法级别或类级别声明泛型类型。
可能会帮助你http://stackoverflow.com/questions/450807/java-generics-how-do-i-make-the-method-return-type-generic – Habib 2012-07-12 05:47:46