Java generic as constructor argument
19:08 01 Mar 2022

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 argument 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 {

        private T payload;

        public T get() {
            return payload;
        }

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

    public interface Processor {

        List> receiveMessages();

        void delete(List> messagePayload);
    }

    public class ProcessorThread {

        private final Processor processor;

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

        public void run() {
            List> 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?

java generics