'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?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source