質問

I am writing a factory class that looks like this:

public class RepositoryFactory<T> {
    public T getRepository(){
        if(T is IQuestionRepository){ // This is where I am not sure
            return new QuestionRepository();
        }
        if(T is IAnswerRepository){ // This is where I am not sure
            return new AnswerRepository();
        }
    }
}

but how can I check it T is a type of specified interface?

役に立ちましたか?

解決

You'll need to create the RepositoryFactory instance by passing in the Class object for the generic type.

public class RepositoryFactory<T> {
    private Class<T> type;
    public RepositoryFactory(Class<T> type) {
        this.type = type;
    }
    public T getRepository(){
        if(type.isAssignableFrom(IQuestionRepository.class)){ //or type.equals(...) for more restrictive
            return new QuestionRepository();
        }
        ...
    }

Otherwise, at runtime, you cannot know the value of the type variable T.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top