1

I'm looking for a way to convert an array of one generic type to another. Here's my use case:

I have a base library with the following Composite:

// leaf
public interface Job<T extends JobResult> {
  public T doJob();
}

public class CompositeJob<T extends JobResult> implements Job<T>{
  private Job<T>[] jobs;
  // ...
}

// component
public interface Worker<T extends JobResult> {
  public T doWork();
  public Job<T>[] getJobs();
  public void addJob(Job<T> job);
}

public class HardWorker<T extends JobResult> implements Worker<T> {
  public T doWork() {
    // ...
  }
}

I also have a custom library that imports the base library, which uses a more domain-specific name for a Job, a "Customer". I'd like users of my custom library to only interface through my Customer types, so I can change the implementation of the base library without disturbing my public API.

I'm hindered because Worker.getJobs() returns an array of Job[]. I'd like to write a method that can convert Job[] to WorkItem[] to prevent exposure of the base library's types, but I'm not sure how to write that conversation method in Java.

Here's the signature of the method I want:

public WorkItem<T1>[] convert(Job<T>[] jobs) {
  for (Job<T> job : jobs) {
    // convert a T to a T1
    // create a new WorkItem using the Job as input
  }
}
2
  • We don't know anything about WorkItem. Commented Jul 18, 2014 at 20:25
  • 1
    I know how to create a new WorkItem from the properties of a Job. Commented Jul 18, 2014 at 20:28

1 Answer 1

4

I'd like to write a method that can convert Job[] to WorkItem[] to prevent exposure of the base library's types.

Adapter Design Pattern might help you in this case specially read Object Adapter pattern section.

Read more Adapter Pattern - GOF

The adapter pattern is a design pattern that is used to allow two incompatible types to communicate. Where one class relies upon a specific interface that is not implemented by another class, the adapter acts as a translator between the two types.

enter image description here

Sign up to request clarification or add additional context in comments.

1 Comment

I had been trying to use an approach of casting, but maybe an Adapter is the way to go. Let me go try this.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.