Cloning with generics

后端 未结 6 483
栀梦
栀梦 2020-12-08 17:19

Once upon a time there was a class:

public class Scope> implements Comparable>, Clon         


        
6条回答
  •  时光说笑
    2020-12-08 17:41

    Hopefully I've resolved the problem of generic cloning in Java:

    public class Generic {
      private T data;
    
      public Generic() {
        // ...
      }
    
      @SuppressWarnings("unchecked")
      @Override
      public Object clone() {
        Generic cloned = new Generic();
        try {
          cloned.data = (T) data.getClass().getMethod("clone").invoke(data);
        } catch (Exception e) {
          // ...
        }
        return cloned;
      }
    }
    

提交回复
热议问题