Shyama Prasad Mohanty
Shyama Prasad Mohanty

Reputation: 53

Generics - The method in the type is not applicable for the arguments

I am using an external library which contains a method :

public <V> List<V> getObjectsForHashCriteria(@NonNull final Class<V> clazz,     @NonNull final V hashObject) {
final DynamoDBQueryExpression<V> queryExpression = new     DynamoDBQueryExpression<V>().withHashKeyValues(hashObject);
return dynamoDBMapper.query(clazz, queryExpression,
            dynamoDBMapperConfig);
}

I want to invoke the above method. To get the class object, I am passing it in the constructor. Something like this :

MyClass(final @NonNull Class<T> clazz){
this.clazz = clazz}

Inorder to invoke the getObjectsForHashCriteria(), I am currently doing it as shown below but it shows compilation error :

public <T> List<T> fetchObjectsForHashCriteria(@NonNull final T hashObject){
instance.getObjectsForHashCriteria(clazz, hashObject);
}

But it shows a compilation error :

The method getObjectsForHashCriteria(Class,V) is not applicable for the arguments (Class,T).

So basically I am trying to pass generic type parameters as generic type arguments. Please let me know what is the issue with this ? If this is not possible, is there any workaround for this ?

Upvotes: 1

Views: 8269

Answers (1)

Jesper
Jesper

Reputation: 206816

You didn't show your complete class MyClass, but I presume it looks like this:

public class MyClass<T> {
    private final Class<T> clazz;
    // ...

    MyClass(final @NonNull Class<T> clazz) {
        this.clazz = clazz;
    }

    public <T> List<T> fetchObjectsForHashCriteria(@NonNull final T hashObject) {
        instance.getObjectsForHashCriteria(clazz, hashObject);
    }
}

What's wrong with this: The method fetchObjectsForHashCriteria has its own type parameter T which is separate from the type parameter T of class MyClass, even though they both happen to be named T.

Remove the type parameter T on the method; let it use the T from the class instead:

// Note: no <T> type parameter
public List<T> fetchObjectsForHashCriteria(@NonNull final T hashObject) {
    instance.getObjectsForHashCriteria(clazz, hashObject);
}

Upvotes: 3

Related Questions