简体   繁体   English

使用 Generics 和接口,返回类型是 Object,而不是类型

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

I have a UseCase interface, simplified to the following我有一个 UseCase 接口,简化为以下

   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.但是,我的执行返回类型不是用户类型,而是 Object 类型。

I would like to better understand how to properly use the generic here, is this the expected output?我想在这里更好地了解如何正确使用泛型,这是预期的 output 吗? I understand that I can cast the Object to User, but I would like to avoid that if I do not need to.我知道我可以将 Object 投射到用户,但如果我不需要,我想避免这种情况。

At runtime one has only Object because of generic type erasure.由于泛型类型擦除,在运行时只有 Object。 Hence one needs probably the class.因此,可能需要 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);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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