简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM