nsa
nsa

Reputation: 199

java template how to return function parameter class type instance with template type

i have template class like this.Msg is the known type

class ResultSet<T extends Msg>
{
}

then in my app class i want to functionality like this.

class App
{
      public ResultSet<? extends Msg> getResult(Class<? extends Msg> cls)
     {
         return new ResultSet();
     }
}

i have message derived from Msg class let's say

class HelloMsg extends Msg
{
  String greeting = null;
}

but i can't use the getResult function

ResultSet<HelloMsg> rs = getResult(HelloMsg.class);

error is : incompatible type : ResultSet ....

please correct the heading as needed.

Upvotes: 0

Views: 288

Answers (2)

nsa
nsa

Reputation: 199

i just found the answer .

class App
{
      public <T extends Msg> ResultSet<T> getResult(Class<T> cls)
     {
         return new ResultSet();
     }
}

Upvotes: 1

Tom
Tom

Reputation: 17567

The problem is this method signature:

public ResultSet<? extends Msg> getResult(Class<? extends Msg> cls)

There is no "connection" between the returned generic type and the parameter type, except the same parent class, because ? is a wildcard. That is why the compiler mentioning incompatible types, since the returned type by a different type as provided as the argument. See this question for more information: java generics : fancy capture collision.

To fix that you could change you App class as follows:

class App<T extends Msg> {
     public ResultSet<T> getResult() { // no need for a method parameter anymore
         return new ResultSet<>(); // don't forget the diamond operator here
     }
}

Upvotes: 1

Related Questions