Using Java generics in an interface to provide an implementation of a method with an implementation type as parameter

I have an interface like this:

public interface DataObject {
    ...
    public void copyFrom(DataObject source);
    ...
}

And the class that implements it:

public class DataObjectImpl implements DataObject {
    ...
    @Override
    public void copyFrom(final DataObject source) {...}

    public void copyFrom(final DataObjectImpl source) {...}
    ...
}

Is there any way to implement the implementation of the method "public void copyFrom (DataObjectImpl source)" in the DataObject interface using generics or otherwise?

+3
source share
2 answers

If you just need to handle it copyFromdifferently, if the given DataObjectone is the same type as the object itself, just do something like this:

public class DataObjectImpl implements DataObject {
  public void copyFrom(final DataObject source) {
    if (source instanceof DataObjectImpl) {
      ...
    }
    else {
      ...
    }
  }
}

, , , . , , .

public interface DataObject<T extends DataObject<T>> {
  public void copyFrom(DataObject source);
  public void copyFromImpl(T source);
}

public class DataObjectImpl implements DataObject<DataObjectImpl> {
  public void copyFrom(final DataObject source) { ... }
  public void copyFromImpl(final DataObjectImpl source) { ... }
}
+4

, :

interface DataObject {
   public <T> void copyFrom(T impl);
}

:

interface DataObject {
   public <T extends DataObject> void copyFrom(T impl);
}

, :

o.copyFrom(new DataObjectImpl());
o.<DataObjectImpl> copyFrom(new DataObjectImpl());

generics, DataObject . , , . , cloning.

, use interfaces only to define types.

:

interface DataObject {
   byte[] getData();
   Long getId();
   Timestamp getCreateDtTm();
}

impl :

class DataObjectImpl implements DataObject {
   // member vars
   public DataObjectImpl(DataObject dataObject) {
      this.data = dataObject.getData();
      this.id = dataObject.getId();
      this.createDtTm = dataObject.getCreateDtTm();
   }
   //getters and setters
}

, .

+3

Source: https://habr.com/ru/post/1771972/


All Articles