1 回答
TA贡献1811条经验 获得超5个赞
在运行时,由于泛型类型擦除,只有对象。因此,人们可能需要一门课程。
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);
}
}
添加回答
举报