简体   繁体   中英

Using Generics with and Interface, Return type is Object, not Type

I have a UseCase interface, simplified to the following

   public interface UseCase<T> {
        T execute(Request request);
   }

An example of an implementation for this would be.

public class DefaultCreateUser implements UseCase<User> {

    private Request request = new CreateUserRequest();

    @Override
    public User execute(Request request) {
        // create newUser based on request here
        return newUser;
    }
}

However, my return type for execute is not of type User, it is of type Object.

I would like to better understand how to properly use the generic here, is this the expected output? I understand that I can cast the Object to User, but I would like to avoid that if I do not need to.

At runtime one has only Object because of generic type erasure. Hence one needs probably the class.

public abstract class AbstractUseCase<T> implements UseCase<T> {

    protected final Class<T> type;

    protected AbstractUseCase(Class<T> type) {
        this.type = type;
    }

    @Override
    public User execute(Request request) {
        // create newUser based on request here
        return newUser;
    }
}

public class DefaultCreateUser extends AbstractUseCase<User> {

    public DefaultCreateUser() {
        super(User.class);
    }

    private Request request = new CreateUserRequest();

    @Override
    public User execute(Request request) {
        return new User();

        // Alternative in the base class:
        T newUser = type.getConstructor().newInstance();
        return newUser;

        // Alternative in the base class:
        Object newUser = ...;
        return type.cast(newUser);
    }
}

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