创建extends泛型对象

  1. public static <T extends Animal> T create(Supplier<T> supplier) {
  2. T t = supplier.get();
  3. t.setName("Tom");
  4. t.setColor("Black");
  5. t.setAge(10);
  6. return t;
  7. }
  8. @Data
  9. static class Animal {
  10. private String name;
  11. private String color;
  12. private Integer age;
  13. }
  14. @Data
  15. @ToString(callSuper = true)
  16. static class Cat extends Animal {
  17. private String hasBanner;
  18. }
  19. @Test
  20. public void testGeneric() {
  21. Animal animal = create(Animal::new);
  22. Cat cat = create(Cat::new);
  23. System.out.println(animal);
  24. System.out.println(cat);
  25. }