Home > Software design >  Java generic as constructor argument
Java generic as constructor argument

Time:03-03

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?

CodePudding user response:

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);
}
  • Related