Java – Uses generic classes as type parameters

Uses generic classes as type parameters… here is a solution to the problem.

Uses generic classes as type parameters

I want to use one generic class as a type parameter of another generic class.

At first my class definition looked like this:

class Foo<T, R extends BaseDto> {}

Then my requirements changed and I had to use wrapper/bearer class types for my R

My attempt so far: (gives compile-time error: Bar<R> expected class or interface).

class Bar<T extends BaseDto> {
    private T dto;
    public Bar(T dto) {
        this.dto= dto;
    }
     getters and setters
}
class Foo<T, Bar<R>> {
    private T entity;
    private R dto;
     getters and setters
}

I can’t use it as Foo<T, Object> because then customers using this class won’t know that they actually need a conversion from Object to Bar

How would I implement such behavior?

Solution

Instead of changing the class header, replace all the places in the class where you use R with Bar<R>

So the class header remains the same:

class Foo<T, R extends CustomClass> 

But suppose you have a field of type R. That needs to be changed to Bar<R>

:

Bar<R> someField;

Related Problems and Solutions