3

I would like to use a generic class as a type parameter for another generic class.

At first my class definition was like this:

class Foo<T, R extends BaseDto> {} 

Then my requirements changed and I had to use a wrapper/holder class for my R type

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

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 not use it as Foo<T, Object> because then the clients using this class would not know that they actually need a cast from Object to Bar.

How would I implement such behaviour?

1
  • 1
    Every answerer here seems to have interpreted the question differently... I suggest you post more code, showing how you expect your class to work before and after the requirement change. Commented Feb 6, 2020 at 8:11

3 Answers 3

3

Instead of changing the class header, replace everywhere in the class where you used R with Bar<R>.

So the class header stays the same:

class Foo<T, R extends CustomClass> 

But let's say you have a field of type R. That needs to be changed to Bar<R>:

Bar<R> someField; 
Sign up to request clarification or add additional context in comments.

1 Comment

I've tried this before and it did not work for my case. After reading your answer, tried this again and found out that the error was on my part. The solution is changing the field type from R to Bar<R>!
0

It looks like what you need may be:

class Foo<T, R extends CustomClass, S extends Bar<R>> 

Comments

0

You would use

class Foo<T extends CustomClass, R extends Bar<T>> {} 

If Bar is fixed, i.e., if the user does not need another class extending Bar, then you need to get rid of R and just use Bar<T> inside Foo

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.