Numeron
Numeron

Reputation: 8833

Java generics - getting a method to return the same type as the first parameter

Something like this is what Im trying to achieve:

public Attribute<?> getAttribute(Class<? extends Attribute> attributeClass){
  for(Attribute attribute: attributes)
    if(attributeClass.isInstance(attribute)) return attributeClass.cast(attribute);
  return null;
}

where the Attribute< ?> is obviously the incorrect part.

I want the return type of this method to be of attributeClass, but I cant seem to figure out how to get that. I should note that I am aware that I could just use Attribute as a return type, but this method would be mostly called in this fashion:

AttributeType1 attributeType1 = getAttribute(AttributeType1.class);

...and I am trying to avoid having to cast every time.

Help appreciated.

Upvotes: 14

Views: 7222

Answers (2)

Kal
Kal

Reputation: 24910

public <T extends Attribute> T getAttribute(Class<T> attributeClass) {

should work

Upvotes: 5

ratchet freak
ratchet freak

Reputation: 48226

this is what you need

public <T extends Attribute> T getAttribute(Class<T> attributeClass){

you need to specify the generic type before the return type

Upvotes: 22

Related Questions