Artjom Prozorov
Artjom Prozorov

Reputation: 127

Make method generic

I have different documents, one document is referring to one client for example and another document to another. I have Pdf(generic) class with methods that are shared between different Pdf documents > then i have a method that transforms a PDDocument type object to Page wrapper class.

How can i instead of creating Page , create a generic and return a lift of client.Page or client1,Page

 public List<Page> splitToPages() {
    try {
        Splitter splitter = new Splitter();
        return splitter.split(getPDDocument()).stream().map(Page::new).collect(Collectors.toList());
    } catch (IOException e) {
        throw new RuntimeException("Document could not be split", e);
    }
}

Thank you

Upvotes: 0

Views: 93

Answers (1)

Andy Turner
Andy Turner

Reputation: 140328

Pass in a Function which takes what comes out of the Splitter, and turns it into the type you want:

 public <T> List<T> splitToPages(Function<? super WhateverSplitterReturns, ? extends T> function) {
    try {
        Splitter splitter = new Splitter();
        return splitter.split(getPDDocument()).stream().map(function).collect(Collectors.toList());
    } catch (IOException e) {
        throw new RuntimeException("Document could not be split", e);
    }
}

which you can call with, e.g.

List<Page> pages = splitToPages(Page::new);

Upvotes: 2

Related Questions