Home > Mobile >  Cannot use generic with Util class in Java
Cannot use generic with Util class in Java

Time:08-06

I have a Util class and there is a static method called csvToEmployees. In order to use this method with different type of request classes, I am trying to convert the class as shown below that takes generic parameter:

public class CsvHelper<T> {

    public List<T> csvToEmployees(InputStream is) {
        
        //code omitted

        for (CSVRecord rec : records) {
            T employee = new T(
                    // ...
            );
            employees.add(employee);
        }
        return employees;
    }
}

I call this method from my service by injecting this util class as shown below:

@Service
@RequiredArgsConstructor
public class EmployeeService {

    private final EmployeeRepository employeeRepository;
    private final CsvHelper<EmployeeRequest> helper;

    public void create(MultipartFile file) {
        List<Employee> employees = helper.csvToEmployees(file.getInputStream()).stream()
                .map(EmployeeRequestMapper::mapToEntity)
                .toList();
       
        // ...
    }
}

My problems are:

1. Is the implementation approach above is ok or not? I mean assuming that there are different kind of requests with the same fields, is using generic with that approach ok?

2. I get "Type parameter 'T' cannot be instantiated directly" error in the T employee = new T( line of util class. How can I fix it?

CodePudding user response:

The best solution, in my opinion, is just creating multiple csvToObject methods inside the classes that you need to process.

I mean if you already know that you’re transforming a stream into a list of employees (it’s “hard coded” in the service method) why would you need to use generics? Just use the method for employees instead.

  • Related