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.
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.
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).
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With