Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (7k points)

I would like to write a method that would return a list of any type without the need to typecast anything.

List<User> users = magicalListGetter(User.class);

List<Vehicle> vehicles = magicalListGetter(Vehicle.class);

List<String> strings = magicalListGetter(String.class);

What would the method signature look like?

1 Answer

0 votes
by (13.1k points)

private Object actuallyT;

public <T> List<T> magicalListGetter(Class<T> klazz) {

    List<T> list = new ArrayList<>();

    list.add(klazz.cast(actuallyT));

    try {

        list.add(klazz.getConstructor().newInstance()); // If default constructor

    } ...

    return list;

}

You can give a generic type parameter to a method too. You would need the correct class instance to create things(klazz.getConstructor().newInstance()).

Want to learn Java? Check put the core Java certification from Intellipaat.

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Apr 3, 2021 in Java by dante07 (13.1k points)
0 votes
1 answer
0 votes
1 answer
asked Jul 17, 2019 in Java by Anvi (10.2k points)

Browse Categories

...