fork download
  1. public class Main {
  2.  
  3. static class Animal { }
  4. static class Dog extends Animal { }
  5. static class Cat extends Animal { }
  6.  
  7. public <T extends Animal>T get(Class<T> type) {
  8. // get the animals somehow
  9. java.util.List<Animal> animals = getList();
  10. for(Animal animal : animals) {
  11. if(type.isInstance(animal)) {
  12. // this casting is safe
  13. return (T)animal;
  14. }
  15. }
  16. // if not found
  17. return null;
  18. }
  19.  
  20. private java.util.List<Animal> getList() {
  21. return java.util.Arrays.asList(new Cat(), new Dog());
  22. }
  23.  
  24. public void test() {
  25. Dog dog = get(Dog.class); // ok
  26. Cat cat = get(Dog.class); // ok, expected compiler error
  27. }
  28.  
  29. public static void main(String[] args) {
  30.  
  31. new Main().test();
  32.  
  33. System.out.println("done");
  34. }
  35. }
Compilation error #stdin compilation error #stdout 0s 0KB
stdin
Standard input is empty
compilation info
Main.java:26: incompatible types
found   : Main.Dog
required: Main.Cat
        Cat cat = get(Dog.class); // ok, expected compiler error
                     ^
Note: Main.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
1 error
stdout
Standard output is empty