How to properly implement the call to clone() in a generic class [Java]











up vote
2
down vote

favorite












I have a generic interface and I have to create a class to implement it. I thought at first this would work fine, putting it in the documentation that the interface requires a class that implements the clone method



genericClass<E extends Cloneable> implements genericInterface<E extends Cloneable>{
E data;

//code

public E get(){
return this.data.clone()
}
}


However this doesn't work in practice



package securedatacontainer;

public class Demo {


public static void main(String args) throws CloneNotSupportedException {

String s = "user";
A a = new A(5, s);
A b = a.clone();
System.out.println("a equals b: " +(a.equals(b)));
System.out.println("a == b: " + (a == b));


B<A> c = new B<>(a);
System.out.println("a equals c.data: " +(a.equals(c.data)));
System.out.println("a == c.data: " + (a == c.data));

A k = c.get();
System.out.println(k.value);

}

}


class A implements Cloneable{
int value;
String name;


public A(int x, String str ){
this.value = x;
this.name = str;
}

@Override
public A clone() throws CloneNotSupportedException {
A temp = new A(this.value, this.name);
return temp;
}


public boolean equals(A elem){
return (this.name).equals(elem.name) && this.value==elem.value;
}
}




class B <E extends Cloneable>{
E data;

public B(E elem){
this.data=elem;
}

public E get() throws CloneNotSupportedException{
return (E) this.data.clone();
}


}


I get



Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - Erroneous sym type: java.lang.Cloneable.clone
at securedatacontainer.B.get(Demo.java:60)
at securedatacontainer.Demo.main(Demo.java:19)


Because the project is supposed to be a data storage, I really doubt my teacher wants some shallow copy of the generic E element (note that is just a simple test program for clone, not the actual project). Can anyone tell me why this does not work or how I can make it work? I can't make any assumption about the input E element, only that it has its own clone() method










share|improve this question




























    up vote
    2
    down vote

    favorite












    I have a generic interface and I have to create a class to implement it. I thought at first this would work fine, putting it in the documentation that the interface requires a class that implements the clone method



    genericClass<E extends Cloneable> implements genericInterface<E extends Cloneable>{
    E data;

    //code

    public E get(){
    return this.data.clone()
    }
    }


    However this doesn't work in practice



    package securedatacontainer;

    public class Demo {


    public static void main(String args) throws CloneNotSupportedException {

    String s = "user";
    A a = new A(5, s);
    A b = a.clone();
    System.out.println("a equals b: " +(a.equals(b)));
    System.out.println("a == b: " + (a == b));


    B<A> c = new B<>(a);
    System.out.println("a equals c.data: " +(a.equals(c.data)));
    System.out.println("a == c.data: " + (a == c.data));

    A k = c.get();
    System.out.println(k.value);

    }

    }


    class A implements Cloneable{
    int value;
    String name;


    public A(int x, String str ){
    this.value = x;
    this.name = str;
    }

    @Override
    public A clone() throws CloneNotSupportedException {
    A temp = new A(this.value, this.name);
    return temp;
    }


    public boolean equals(A elem){
    return (this.name).equals(elem.name) && this.value==elem.value;
    }
    }




    class B <E extends Cloneable>{
    E data;

    public B(E elem){
    this.data=elem;
    }

    public E get() throws CloneNotSupportedException{
    return (E) this.data.clone();
    }


    }


    I get



    Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - Erroneous sym type: java.lang.Cloneable.clone
    at securedatacontainer.B.get(Demo.java:60)
    at securedatacontainer.Demo.main(Demo.java:19)


    Because the project is supposed to be a data storage, I really doubt my teacher wants some shallow copy of the generic E element (note that is just a simple test program for clone, not the actual project). Can anyone tell me why this does not work or how I can make it work? I can't make any assumption about the input E element, only that it has its own clone() method










    share|improve this question


























      up vote
      2
      down vote

      favorite









      up vote
      2
      down vote

      favorite











      I have a generic interface and I have to create a class to implement it. I thought at first this would work fine, putting it in the documentation that the interface requires a class that implements the clone method



      genericClass<E extends Cloneable> implements genericInterface<E extends Cloneable>{
      E data;

      //code

      public E get(){
      return this.data.clone()
      }
      }


      However this doesn't work in practice



      package securedatacontainer;

      public class Demo {


      public static void main(String args) throws CloneNotSupportedException {

      String s = "user";
      A a = new A(5, s);
      A b = a.clone();
      System.out.println("a equals b: " +(a.equals(b)));
      System.out.println("a == b: " + (a == b));


      B<A> c = new B<>(a);
      System.out.println("a equals c.data: " +(a.equals(c.data)));
      System.out.println("a == c.data: " + (a == c.data));

      A k = c.get();
      System.out.println(k.value);

      }

      }


      class A implements Cloneable{
      int value;
      String name;


      public A(int x, String str ){
      this.value = x;
      this.name = str;
      }

      @Override
      public A clone() throws CloneNotSupportedException {
      A temp = new A(this.value, this.name);
      return temp;
      }


      public boolean equals(A elem){
      return (this.name).equals(elem.name) && this.value==elem.value;
      }
      }




      class B <E extends Cloneable>{
      E data;

      public B(E elem){
      this.data=elem;
      }

      public E get() throws CloneNotSupportedException{
      return (E) this.data.clone();
      }


      }


      I get



      Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - Erroneous sym type: java.lang.Cloneable.clone
      at securedatacontainer.B.get(Demo.java:60)
      at securedatacontainer.Demo.main(Demo.java:19)


      Because the project is supposed to be a data storage, I really doubt my teacher wants some shallow copy of the generic E element (note that is just a simple test program for clone, not the actual project). Can anyone tell me why this does not work or how I can make it work? I can't make any assumption about the input E element, only that it has its own clone() method










      share|improve this question















      I have a generic interface and I have to create a class to implement it. I thought at first this would work fine, putting it in the documentation that the interface requires a class that implements the clone method



      genericClass<E extends Cloneable> implements genericInterface<E extends Cloneable>{
      E data;

      //code

      public E get(){
      return this.data.clone()
      }
      }


      However this doesn't work in practice



      package securedatacontainer;

      public class Demo {


      public static void main(String args) throws CloneNotSupportedException {

      String s = "user";
      A a = new A(5, s);
      A b = a.clone();
      System.out.println("a equals b: " +(a.equals(b)));
      System.out.println("a == b: " + (a == b));


      B<A> c = new B<>(a);
      System.out.println("a equals c.data: " +(a.equals(c.data)));
      System.out.println("a == c.data: " + (a == c.data));

      A k = c.get();
      System.out.println(k.value);

      }

      }


      class A implements Cloneable{
      int value;
      String name;


      public A(int x, String str ){
      this.value = x;
      this.name = str;
      }

      @Override
      public A clone() throws CloneNotSupportedException {
      A temp = new A(this.value, this.name);
      return temp;
      }


      public boolean equals(A elem){
      return (this.name).equals(elem.name) && this.value==elem.value;
      }
      }




      class B <E extends Cloneable>{
      E data;

      public B(E elem){
      this.data=elem;
      }

      public E get() throws CloneNotSupportedException{
      return (E) this.data.clone();
      }


      }


      I get



      Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - Erroneous sym type: java.lang.Cloneable.clone
      at securedatacontainer.B.get(Demo.java:60)
      at securedatacontainer.Demo.main(Demo.java:19)


      Because the project is supposed to be a data storage, I really doubt my teacher wants some shallow copy of the generic E element (note that is just a simple test program for clone, not the actual project). Can anyone tell me why this does not work or how I can make it work? I can't make any assumption about the input E element, only that it has its own clone() method







      java generics clone






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 11 at 15:27

























      asked Nov 11 at 15:22









      Dario

      133




      133
























          1 Answer
          1






          active

          oldest

          votes

















          up vote
          0
          down vote



          accepted










          Because the clone method is marked as protected on the Object class, you cannot in general call this method on arbitrary objects. The idea behind the clone() method is that classes which supported it would override the method, declaring it as public.



          The only real solution here that preserves full functionality is to use reflection to access the method and get around the access modifiers.



          So here's my solution,



          public class B<E extends Cloneable> {
          E data;

          public B(E elem) {
          this.data = elem;
          }

          @SuppressWarnings("unchecked")
          public E get() {
          Method clone = null;
          try {
          clone = data.getClass().getMethod("clone");
          Object args = new Object[0];
          return (E) clone.invoke(data, args);
          } catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException
          | InvocationTargetException e) {
          throw new RuntimeException(e);
          }

          }
          }


          Clonable determines the behavior of Object’s protected clone implementation: if a class implements Cloneable, Object’s clone method returns a field-by-field copy of the object; otherwise it throws CloneNotSupportedException. But the way you have implemented the clone method in class A does not call Object's clone method so this has no effect.



          @Override
          public A clone() throws CloneNotSupportedException {
          A temp = new A(this.value, this.name);
          return temp;
          }


          If you want to make use of that facility you have to implement it like so,



          public class A implements Cloneable {
          int value;
          String name;

          public A(int x, String str) {
          this.value = x;
          this.name = str;
          }

          @Override
          public A clone() throws CloneNotSupportedException {
          return (A) super.clone();
          }

          public boolean equals(A elem) {
          return (this.name).equals(elem.name) && this.value == elem.value;
          }
          }


          In this case if your class A does not implement Cloneable then the java.lang.CloneNotSupportedException will be thrown.



          Finally the declaration public class B<E extends Cloneable> gives you a compiler error if you try to pass in something that does not implement Cloneable to the B constructor in your Demo class.



          B<A> c = new B<>(doesNotImplCloneable);   // Gives a compilation error.


          So if you are using the Object's clone method as I have shown here the extends/implements Cloneable is the way to go.






          share|improve this answer



















          • 1




            Thanks, your answer gave me an insight on the matter. If I'm fetching the clone() method directly this way, does "extends/implements Cloneable" serve any purpose? Can I just use invoke(data) instead of invoke(data, args)?
            – Dario
            Nov 11 at 18:16










          • Very good question, and I have updated my answer above.
            – Ravindra Ranwala
            Nov 12 at 2:31











          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53250170%2fhow-to-properly-implement-the-call-to-clone-in-a-generic-class-java%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes








          up vote
          0
          down vote



          accepted










          Because the clone method is marked as protected on the Object class, you cannot in general call this method on arbitrary objects. The idea behind the clone() method is that classes which supported it would override the method, declaring it as public.



          The only real solution here that preserves full functionality is to use reflection to access the method and get around the access modifiers.



          So here's my solution,



          public class B<E extends Cloneable> {
          E data;

          public B(E elem) {
          this.data = elem;
          }

          @SuppressWarnings("unchecked")
          public E get() {
          Method clone = null;
          try {
          clone = data.getClass().getMethod("clone");
          Object args = new Object[0];
          return (E) clone.invoke(data, args);
          } catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException
          | InvocationTargetException e) {
          throw new RuntimeException(e);
          }

          }
          }


          Clonable determines the behavior of Object’s protected clone implementation: if a class implements Cloneable, Object’s clone method returns a field-by-field copy of the object; otherwise it throws CloneNotSupportedException. But the way you have implemented the clone method in class A does not call Object's clone method so this has no effect.



          @Override
          public A clone() throws CloneNotSupportedException {
          A temp = new A(this.value, this.name);
          return temp;
          }


          If you want to make use of that facility you have to implement it like so,



          public class A implements Cloneable {
          int value;
          String name;

          public A(int x, String str) {
          this.value = x;
          this.name = str;
          }

          @Override
          public A clone() throws CloneNotSupportedException {
          return (A) super.clone();
          }

          public boolean equals(A elem) {
          return (this.name).equals(elem.name) && this.value == elem.value;
          }
          }


          In this case if your class A does not implement Cloneable then the java.lang.CloneNotSupportedException will be thrown.



          Finally the declaration public class B<E extends Cloneable> gives you a compiler error if you try to pass in something that does not implement Cloneable to the B constructor in your Demo class.



          B<A> c = new B<>(doesNotImplCloneable);   // Gives a compilation error.


          So if you are using the Object's clone method as I have shown here the extends/implements Cloneable is the way to go.






          share|improve this answer



















          • 1




            Thanks, your answer gave me an insight on the matter. If I'm fetching the clone() method directly this way, does "extends/implements Cloneable" serve any purpose? Can I just use invoke(data) instead of invoke(data, args)?
            – Dario
            Nov 11 at 18:16










          • Very good question, and I have updated my answer above.
            – Ravindra Ranwala
            Nov 12 at 2:31















          up vote
          0
          down vote



          accepted










          Because the clone method is marked as protected on the Object class, you cannot in general call this method on arbitrary objects. The idea behind the clone() method is that classes which supported it would override the method, declaring it as public.



          The only real solution here that preserves full functionality is to use reflection to access the method and get around the access modifiers.



          So here's my solution,



          public class B<E extends Cloneable> {
          E data;

          public B(E elem) {
          this.data = elem;
          }

          @SuppressWarnings("unchecked")
          public E get() {
          Method clone = null;
          try {
          clone = data.getClass().getMethod("clone");
          Object args = new Object[0];
          return (E) clone.invoke(data, args);
          } catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException
          | InvocationTargetException e) {
          throw new RuntimeException(e);
          }

          }
          }


          Clonable determines the behavior of Object’s protected clone implementation: if a class implements Cloneable, Object’s clone method returns a field-by-field copy of the object; otherwise it throws CloneNotSupportedException. But the way you have implemented the clone method in class A does not call Object's clone method so this has no effect.



          @Override
          public A clone() throws CloneNotSupportedException {
          A temp = new A(this.value, this.name);
          return temp;
          }


          If you want to make use of that facility you have to implement it like so,



          public class A implements Cloneable {
          int value;
          String name;

          public A(int x, String str) {
          this.value = x;
          this.name = str;
          }

          @Override
          public A clone() throws CloneNotSupportedException {
          return (A) super.clone();
          }

          public boolean equals(A elem) {
          return (this.name).equals(elem.name) && this.value == elem.value;
          }
          }


          In this case if your class A does not implement Cloneable then the java.lang.CloneNotSupportedException will be thrown.



          Finally the declaration public class B<E extends Cloneable> gives you a compiler error if you try to pass in something that does not implement Cloneable to the B constructor in your Demo class.



          B<A> c = new B<>(doesNotImplCloneable);   // Gives a compilation error.


          So if you are using the Object's clone method as I have shown here the extends/implements Cloneable is the way to go.






          share|improve this answer



















          • 1




            Thanks, your answer gave me an insight on the matter. If I'm fetching the clone() method directly this way, does "extends/implements Cloneable" serve any purpose? Can I just use invoke(data) instead of invoke(data, args)?
            – Dario
            Nov 11 at 18:16










          • Very good question, and I have updated my answer above.
            – Ravindra Ranwala
            Nov 12 at 2:31













          up vote
          0
          down vote



          accepted







          up vote
          0
          down vote



          accepted






          Because the clone method is marked as protected on the Object class, you cannot in general call this method on arbitrary objects. The idea behind the clone() method is that classes which supported it would override the method, declaring it as public.



          The only real solution here that preserves full functionality is to use reflection to access the method and get around the access modifiers.



          So here's my solution,



          public class B<E extends Cloneable> {
          E data;

          public B(E elem) {
          this.data = elem;
          }

          @SuppressWarnings("unchecked")
          public E get() {
          Method clone = null;
          try {
          clone = data.getClass().getMethod("clone");
          Object args = new Object[0];
          return (E) clone.invoke(data, args);
          } catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException
          | InvocationTargetException e) {
          throw new RuntimeException(e);
          }

          }
          }


          Clonable determines the behavior of Object’s protected clone implementation: if a class implements Cloneable, Object’s clone method returns a field-by-field copy of the object; otherwise it throws CloneNotSupportedException. But the way you have implemented the clone method in class A does not call Object's clone method so this has no effect.



          @Override
          public A clone() throws CloneNotSupportedException {
          A temp = new A(this.value, this.name);
          return temp;
          }


          If you want to make use of that facility you have to implement it like so,



          public class A implements Cloneable {
          int value;
          String name;

          public A(int x, String str) {
          this.value = x;
          this.name = str;
          }

          @Override
          public A clone() throws CloneNotSupportedException {
          return (A) super.clone();
          }

          public boolean equals(A elem) {
          return (this.name).equals(elem.name) && this.value == elem.value;
          }
          }


          In this case if your class A does not implement Cloneable then the java.lang.CloneNotSupportedException will be thrown.



          Finally the declaration public class B<E extends Cloneable> gives you a compiler error if you try to pass in something that does not implement Cloneable to the B constructor in your Demo class.



          B<A> c = new B<>(doesNotImplCloneable);   // Gives a compilation error.


          So if you are using the Object's clone method as I have shown here the extends/implements Cloneable is the way to go.






          share|improve this answer














          Because the clone method is marked as protected on the Object class, you cannot in general call this method on arbitrary objects. The idea behind the clone() method is that classes which supported it would override the method, declaring it as public.



          The only real solution here that preserves full functionality is to use reflection to access the method and get around the access modifiers.



          So here's my solution,



          public class B<E extends Cloneable> {
          E data;

          public B(E elem) {
          this.data = elem;
          }

          @SuppressWarnings("unchecked")
          public E get() {
          Method clone = null;
          try {
          clone = data.getClass().getMethod("clone");
          Object args = new Object[0];
          return (E) clone.invoke(data, args);
          } catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException
          | InvocationTargetException e) {
          throw new RuntimeException(e);
          }

          }
          }


          Clonable determines the behavior of Object’s protected clone implementation: if a class implements Cloneable, Object’s clone method returns a field-by-field copy of the object; otherwise it throws CloneNotSupportedException. But the way you have implemented the clone method in class A does not call Object's clone method so this has no effect.



          @Override
          public A clone() throws CloneNotSupportedException {
          A temp = new A(this.value, this.name);
          return temp;
          }


          If you want to make use of that facility you have to implement it like so,



          public class A implements Cloneable {
          int value;
          String name;

          public A(int x, String str) {
          this.value = x;
          this.name = str;
          }

          @Override
          public A clone() throws CloneNotSupportedException {
          return (A) super.clone();
          }

          public boolean equals(A elem) {
          return (this.name).equals(elem.name) && this.value == elem.value;
          }
          }


          In this case if your class A does not implement Cloneable then the java.lang.CloneNotSupportedException will be thrown.



          Finally the declaration public class B<E extends Cloneable> gives you a compiler error if you try to pass in something that does not implement Cloneable to the B constructor in your Demo class.



          B<A> c = new B<>(doesNotImplCloneable);   // Gives a compilation error.


          So if you are using the Object's clone method as I have shown here the extends/implements Cloneable is the way to go.







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Nov 12 at 2:30

























          answered Nov 11 at 16:29









          Ravindra Ranwala

          8,01931533




          8,01931533








          • 1




            Thanks, your answer gave me an insight on the matter. If I'm fetching the clone() method directly this way, does "extends/implements Cloneable" serve any purpose? Can I just use invoke(data) instead of invoke(data, args)?
            – Dario
            Nov 11 at 18:16










          • Very good question, and I have updated my answer above.
            – Ravindra Ranwala
            Nov 12 at 2:31














          • 1




            Thanks, your answer gave me an insight on the matter. If I'm fetching the clone() method directly this way, does "extends/implements Cloneable" serve any purpose? Can I just use invoke(data) instead of invoke(data, args)?
            – Dario
            Nov 11 at 18:16










          • Very good question, and I have updated my answer above.
            – Ravindra Ranwala
            Nov 12 at 2:31








          1




          1




          Thanks, your answer gave me an insight on the matter. If I'm fetching the clone() method directly this way, does "extends/implements Cloneable" serve any purpose? Can I just use invoke(data) instead of invoke(data, args)?
          – Dario
          Nov 11 at 18:16




          Thanks, your answer gave me an insight on the matter. If I'm fetching the clone() method directly this way, does "extends/implements Cloneable" serve any purpose? Can I just use invoke(data) instead of invoke(data, args)?
          – Dario
          Nov 11 at 18:16












          Very good question, and I have updated my answer above.
          – Ravindra Ranwala
          Nov 12 at 2:31




          Very good question, and I have updated my answer above.
          – Ravindra Ranwala
          Nov 12 at 2:31


















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.





          Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


          Please pay close attention to the following guidance:


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53250170%2fhow-to-properly-implement-the-call-to-clone-in-a-generic-class-java%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Bressuire

          Vorschmack

          Quarantine