简体   繁体   中英

How to use type parameter within method declaration instead of class

I have this code which work:

Interface:

public interface Queries<T> {
    List<User> runQuery(T query);
}

and using the interface:

public class UserQueries implements Queries<UserQuery> {

    @Override
    List<User> runQuery(UserQuery q){
    }
}

I want to replace the above with the following code, however, it does not work:

New Interface:

public interface Queries {
     // I want to pass the type parameter within the abstract method instead of the using Queries<T>
    <T> List<User> runQuery(T query);
}

and using the new Interface (version 2):

public class UserQueries implements Queries {

    // does not work, compiler complains:
    // "The method runQuery(UserQuery) of type UserQueries must override or implement a supertype method
    @Override
    List<User> runQuery(UserQuery q) {
    }
}

How can I use type parameter <T> within method intead of class?

You are trying to mix 2 concepts one is generics and another is inheritance.

Version 1 In version 1 you have generic interface

public interface Queries<T>

And in the implementation you are restricting it to accept UserQuery type

public class UserQueries implements Queries<UserQuery> {

Version 2 In version 2 you have concrete interface with generic abstract method

public interface Queries {
 // I want to pass the type parameter within the abstract method instead of the using Queries<T>
<T> List<User> runQuery(T query);
}

So if you implement Queries interface then you have to provide implementations of all abstract methods (if you change the method signature or syntax of method, that method is considered as different method in class but not the abstract method in interface)

This is happening due to Java's Type Erasures . What is happening here is that after compilation this code <T> List<User> runQuery(T query) is changing to List<User> runQuery(Object query) . So that's why in child class you can't use the concrete implementation.

For you reference: Type Erasures in Java

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM