0

I'm Trying to create a copy of the data Object passed as argument and assigning it to the data member variable in the following class (Includes what I've tried so far)

public abstract class AbstractVertex implements Vertex {
private String label;
private Object data;

public AbstractVertex(String label, Object data) {
    this.label = label;

    //What I've tried so far :
    //Method #1
    if(!(data instanceof Cloneable)){
        throw new RuntimeException("data's class doesn't implement a custom clone method");
    }
    this.data = data.clone();

    //Method #2 (Just to get the idea behind this method, syntax may be completely wrong)
    if(( data.getClass().getMethod(clone()) ) == null){
        throw new RuntimeException("data's class doesn't implement a custom clone method");
    }
  }
}

So my problem is that I can't implement any of these methods because the clone() method in the Object class is protected. But since I need to be able to store any type of data in the class AbstractVertex , I absolutely have to make sure the stored data is actually a copy of the one passed in parameter and not passed by reference.

So, how do I tackle this problem?

N.B: This is the abstract class, inheriting class will use this constructor.

Imad
  • 2,358
  • 5
  • 26
  • 55

1 Answers1

1

First of all your method 2 is wrong, not just syntax but logic. In java every class is a subclass of Object and since Object has a protected clone() method, whether they implement Cloneable or not every class has a protected clone() method. So someObject.getClassc().getMethod("clone") never returns null.

As for your method 1, since clone() method is protected you need to call it using reflection like this;

    //Method #1
    if(!(data instanceof Cloneable)){
        throw new RuntimeException("data's class doesn't implement a custom clone method");
    }
    Method cloneMethod = data.getClass().getMethod("clone");
    this.data = cloneMethod.invoke(data);

Also i think you should take a look at this question: About Java cloneable. Using deep-cloning and shallow-cloning like it is mentioned in the link is the practice you should implement.

Community
  • 1
  • 1
Onur
  • 5,617
  • 3
  • 26
  • 35