通用方法接收通用枚举

时间:2016-12-15 08:20:02

标签: java generics methods enums

我希望我的泛型方法接收一个枚举类型,其中包含我希望从该方法返回的类。

所以这就是我得到了多远(例如):

public class Zoo {
   public Monkey apu;
   public Lion simba;
   public Bird zazu;

   public <T extends Animal> T getAnimal(String animal, Animaltype animaltype){
      switch(animal){
         case "apu":
            return animaltype.getType().cast(zoo.feedAnimal(animaltype.getType()))
         case "simba":
            return ??????????????
         case "zazu":
            return ??????????????
      }
   }
}

public enum Animaltype {
   MONKEY(Monkey.class),
   LION(Lion.class),
   BIRD(Bird.class);

   Class <?> enumClass;

   Animaltype(Class<?> enumClass) {
      this.enumClass = enumClass;
   }

   public Class<?> getType(){
      return this.enumClass;
   }
}

现在它在回程中说所需的是T,找到的是对象。

错误信息是: “不兼容的类型必需:T找到了Java.lang.Object

我不知道正确的语法

1 个答案:

答案 0 :(得分:0)

它不起作用,因为Java不知道Animal的类型是什么。

可能的解决方案之一就是返回public Animal getAnimal(String animal, Animaltype animaltype) 。在这种情况下,你不需要任何演员。

T

此外,您可以通过将Class<T>传递给方法而不是Animaltype animaltype来指定public <T extends Animal> T getAnimal(String animal, Class<T> animaltypeClass){ switch(animal){ case "apu": return animaltypeClass.cast(zoo.feedAnimal(animaltypeClass)) ... } } 的类型。

enumClass

但您的枚举中的字段Class <? extends Animal> enumClass;应为public List<RecommenderItem> GetMergedRecommendationLists(List<Restaurant> restaurantRecommendations, List<Dish> dishRecommendations) { //Setting up the output list. List<RecommenderItem> output = new List<RecommenderItem>(); int count = Math.Min(restaurantRecommendations.Count, dishRecommendations.Count); for (int i = 0; i < count; i++) { var restRecommendation = restaurantRecommendations[i]; var dishRecommendation = dishRecommendations[i]; output.Add(new RecommenderItem() { Id = restRecommendation.Id, Entity = restRecommendation }); output.Add(new RecommenderItem() { Id = dishRecommendation.Id, Entity = dishRecommendation }); } int remainingRestaurant = restaurantRecommendations.Count - count; int remainingDishes = dishRecommendations.Count - count; if (remainingRestaurant > 0) { for (int i = count; i < restaurantRecommendations.Count; i++) { var restRecommendation = restaurantRecommendations[i]; output.Add(new RecommenderItem() { Id = restRecommendation.Id, Entity = restRecommendation }); } } else if (remainingDishes > 0) { for (int i = count; i < dishRecommendations.Count; i++) { var dishRecommendation = dishRecommendations[i]; output.Add(new RecommenderItem() { Id = dishRecommendation.Id, Entity = dishRecommendation }); } } return output; }