简体   繁体   中英

How to return generic type from a method in java

I'm new to generics. Here are my classes.

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");    
   }    
}

Now I want these classes to be used in a generic way.

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    
   }    
}

How can I return the generic type (may be a Cat or Dog) from the methods "method1" and "method2". I've several such methods that returns "T extends Animal", so is it better to declare the generic type in a method level or class level.

You cannot have a method returning a generic type, and expect to be able to access that type in the caller of the method without a cast, unless that type can be deduced from the arguments to the method. So the examples in your main won't work.

So you either go without generics, and either cast the return type manually

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

or have the method return the subclass type to start with.

public Dog method1()
    Dog dog = method1()

Or you can go with generics, and either specify the type when calling the method

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

or pass some argument from which the type can be deduced (which the second method already satisfies):

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

Also nituce that you only can call method1 from static main if it is static itself.

The method1 simply says it returns an Animal. Return any instance of Animal, and the code will compile:

return new Dog();

The second method says that it returns an animal which is of the same type than the animal given as argument. So you could return the argument itself, and it would compile. You've said which type the method must return, but you haven't said what the method must do and return, so it's impossible to implement it. All I can say is that return animal; would compile.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM