简体   繁体   中英

extend generic class which should be less generic

I'm reading from the database into 2 classes that have nothing in common in batches. Each batch is stored later on a batch class that extends ArrayList Now I need to take each of the objects in each batch and send some of it fields as a JSON over rabbitMQ.

Code:

public class ObjectA {
  // Some members and methods
}

public class ObjectB {
  // Some members and methods
}

public class BatchA extends ArrayList<ObjectA> {
  // Some methods for ObjecetA
}

public class BatchB extends ArrayList<ObjectB> {
  // Some methods for ObjectB
}

public class EventClass {

    public void sendEvent(final BatchA batch) {
        // send over rabbit
    }

    public void sendEvent(final BatchB batch) {
        // same code as above
    }
}

In order to avoid this duplication of code in EventClass I've created an interface for both ObjecetA and ObjectB and a base class for all batches (as shown below).

Code:

public interface SomeInterface {
    String doSomething();
}

public class ObjectA implements SomeInterface {
    @Override
    public String doSomething() {
        return "Hello, world!";
    }

    public String doSomethingElse() {
        return "Goodbye, world!";
    }
}

public class ObjectB implements SomeInterface {
    @Override
    public String doSomething() {
        return "Hello universe!";
    }

    public String justDo() {
        return "I'm just doing stuff...";
    }
}

public class BasicBatch<T> extends ArrayList<SomeInterface> {
}

public class BatchA extends BasicBatch<ObjectA> {
    public void doBatch() {
        for (int i = 0; i < size(); i++) {
            System.out.println(get(i).doSomethingElse());
        }
    }
}

public class BatchB extends ArrayList<SomeInterface> {
    public void doBatch() {
        for (int i = 0; i < size(); i++) {
            System.out.println(get(i).justDo());
        }
    }
}

I understand that this cannot be done (this code doesn't even compile) - but I'm not sure that is the best way to avoid writing the same method in EventClass over and over for each batch type

How about:

public <T> void sendEvent(final List <? extends T> batch, Function <T, String> toJson) {
    batch .forEach (value -> {
         String json = toJson (value);
         // send over rabbit
    });
}

(I'm writing on a phone, sorry for syntax errors)

您可以尝试将 where 属性添加到您的类中。

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