如何从java中的方法返回泛型类型

时间:2012-07-12 05:43:24

标签: java generics

我是仿制药的新手。这是我的课程。

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”,所以最好在方法级别或类级别声明泛型类型。

2 个答案:

答案 0 :(得分: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)

另请注意,如果method1本身为static main,您只能致电static {/ 1}}。

答案 1 :(得分:0)

方法1简单地说它返回一个Animal。返回Animal的任何实例,代码将编译:

return new Dog();

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

相关问题