2

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?

insomniac
  • 11,146
  • 6
  • 44
  • 55
Tarik
  • 79,711
  • 83
  • 236
  • 349

1 Answers1

8

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.

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724