공부
[Java] Generic method
승가비
2020. 6. 7. 15:45
728x90
private Object o;
public <T> List<T> magicalListGetter(Class<T> klazz) {
List<T> list = new ArrayList<>();
list.add(klazz.cast(o));
try {
list.add(klazz.getConstructor().newInstance());
}
return list;
}
https://stackoverflow.com/questions/17840483/how-to-have-java-method-return-generic-list-of-any-type
How to have Java method return generic list of any type?
I would like to write a method that would return a java.util.List of any type without the need to typecast anything: List users = magicalListGetter(User.class); List ve...
stackoverflow.com
public <T extends Animal> T callFriend(String name, Class<T> type) {
return type.cast(friends.get(name));
}
jerry.callFriend("spike", Dog.class).bark();
jerry.callFriend("quacker", Duck.class).quack();
https://stackoverflow.com/questions/450807/how-do-i-make-the-method-return-type-generic
How do I make the method return type generic?
Consider this example (typical in OOP books): I have an Animal class, where each Animal can have many friends. And subclasses like Dog, Duck, Mouse etc which add specific behavior like bark(), q...
stackoverflow.com
728x90