2012-07-12 145 views
0

我是新来的泛型。这是我的课程。如何从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”,所以最好在方法级别或类级别声明泛型类型。

+3

可能会帮助你http://stackoverflow.com/questions/450807/java-generics-how-do-i-make-the-method-return-type-generic – Habib 2012-07-12 05:47:46

回答

1

你不能有一个方法返回一个泛型类型,并希望能够在没有强制转换的情况下在方法的调用者中访问该类型,除非该类型可以从该方法的参数中推导出来。因此main中的示例将不起作用。

所以,你要么去没有泛型,并且或者把返回式手动

public Animal method1() 
    Dog dog = (Dog)method1() 

还是有方法返回子类类型开始。

public Dog method1() 
    Dog dog = method1() 

或者你可以使用泛型去,要么指定类型调用方法

public <T extends Animal> T method1() 
    Dog dog = <Dog>method1() 

时,或通过一些参数从中型可以推断(这第二种方法已经满足):

public <T extends Animal> T method1(Class<T> classOfreturnedType) 
    Dog dog = method1(Dog.class) 

而且nituce,你只能调用method1static main如果static本身。

+0

非常感谢你。 – user1519735 2012-07-12 06:25:20

0

该方法1只是说它返回一个动物。返回动物的任何实例,并且代码将编译:

return new Dog(); 

第二种方法说,它返回一个动物,其是相同的类型比给定为参数的动物。所以你可以返回参数本身,然后编译。你已经说过哪种类型的方法必须返回,但是你没有说明该方法必须做什么并返回,所以不可能实现它。我只能说return animal;会编译。