Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 912
Numeron Avatar asked Jun 09 '11 02:06

Numeron


People also ask

Can generics take multiple type parameters?

Multiple parametersYou can also use more than one type parameter in generics in Java, you just need to pass specify another type parameter in the angle brackets separated by comma.

How do you declare a generic bounded type parameter in Java?

To declare a bounded type parameter, list the type parameter's name, followed by the extends keyword, followed by its upper bound, which in this example is Number . Note that, in this context, extends is used in a general sense to mean either "extends" (as in classes) or "implements" (as in interfaces).

How do I restrict a generic type in Java?

Whenever you want to restrict the type parameter to subtypes of a particular class you can use the bounded type parameter. If you just specify a type (class) as bounded parameter, only sub types of that particular class are accepted by the current generic class.


1 Answers

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

like image 78
ratchet freak Avatar answered Oct 28 '22 21:10

ratchet freak