krinklesaurus
krinklesaurus

Reputation: 1686

Java generic as constructor argument

I have three classes, Processor is meant to process different types of Message which is typed. The code shown here is not working, I suppose it's because it cannot be guaranteed that the processor arguement in the constructor has the same type as the one in the run method, and it also cannot be guaranteed that the receiveMessage method returns the same type as delete() accepts.

    public class Message<T> {

        private T payload;

        public T get() {
            return payload;
        }

        public void set(T payload) {
            this.payload = payload;
        }

    }

    public interface Processor<T> {

        List<Message<T>> receiveMessages();

        void delete(List<Message<T>> messagePayload);

    }

    public class ProcessorThread {

        private final Processor<?> processor;

        public ProcessorThread(final Processor<?> processor) {
            this.processor = processor;
        }

        public void run() {
            List<Message<?>> messages = this.processor.receiveMessages();

            processor.delete(messages);
        }

    }

Is there a way to be typesafe without having to type the ProcessorThread class? Maybe passing the message payload class type around or so?

Upvotes: 0

Views: 50

Answers (1)

shmosel
shmosel

Reputation: 50776

You can create a generic method to capture the type:

public void run() {
    runGeneric(this.processor);
}

private static <T> void runGeneric(Processor<T> processor) {
    List<Message<T>> messages = processor.receiveMessages();
    processor.delete(messages);
}

Upvotes: 2

Related Questions