2

A method with this signature constructs an object of class objClass which is somewhere in the BaseModel hierarchy, and adds it to the list with ? extends BaseModel objects.

public void constructAndAdd(List<? extends BaseModel> list, Class objClass)
{
   BaseModel newObject = (BaseModel)objClass.newInstance();
   list.add(newObject);
}

Error:

The method add(capture#2-of ? extends BaseModel) in the type List<capture#2-of ? extends BaseModel> is not applicable for the arguments (BaseModel)

I wish I could do

? extends BaseModel newObject = (? extends BaseModel)objClass.newInstance();

but that syntax is wrong.

3
  • Try changing "List<? extends BaseModel>" list to "List<BaseModel> list" Commented Dec 27, 2015 at 22:24
  • But my list contains object of a subtype of BaseModel, not BaseModel itself. The solution provided by SLaks is correct, I have to specify generics in the method signature. Commented Dec 27, 2015 at 22:34
  • @Pshemo: Yes, because T will be that derived class. Commented Dec 27, 2015 at 23:54

2 Answers 2

5

The compiler cannot know that the ? is the same type of the class.

You need to make the method itself generic, so that you can actually refer to that type:

public <T extends BaseModel> void constructAndAdd(List<? super T> list, Class<? extends T> objClass) {
    list.add(objClass.newInstance());
}

Once you do that, you don't need any casts at all.

Sign up to request clarification or add additional context in comments.

Comments

2

List<? extends BaseModel> list can hold lists of any type of elements extending BaseModel. So lets say that user passed to it list of FooBaseModel elements, where FooBaseModel is class which extends BaseModel but introduces some additional fields/methods. Now would it be safe if we could add to that list any BaseModel?

No because when we use list.get();, we expect it to return instance of FooBaseModel on which we could safely invoke these additional methods.

Another problem is that objClass.newInstance() could return other type which extends BaseModel but behaves in different way than FooBaseModel would expect.

So you can't add any element to list defined as List<? extends OtherType>.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.