George
George

Reputation: 4109

How to implement this generic method in Java?

I got an interface just like this

public interface Reader<T> {
    T read(Class<T> type,InputStream in);
}

It's a general interface intended to read an object of type T from a stream. Then I know all objects I will deal are subclasses of, let's say S. So I create this

public class SReader implements Reader<S>{
    S read(Class<S> type, InputStream in){
        // do the job here
    }
}

But Class<S1> cannot assigned to Class<S> even though S1 is a subclass of S. How do I implement this elegantly? Bounded type parameter? I am not figure that out. The only solution I have is just remove the type parameter like

public class SReader implements Reader{
    // the other stuff
}

Upvotes: 2

Views: 100

Answers (1)

Louis Wasserman
Louis Wasserman

Reputation: 198211

It sounds like you want

public interface Reader<T> {
    T read(Class<? extends T> type,InputStream in);
}

Upvotes: 8

Related Questions