Search code examples
javagenericsclone

clone() not visible


I have a class:

public class CounterBag<T extends Additive<T> & Cloneable & Serializable> {
    private T cntData;

    // c'tor, accessors equals and hashcode... 
    public T getCounterData() {
       return cntData;
    }
}

other class Service has a member of type Set<CounterBag>. Now inside the Service I want to lookup for specific CounterBag and return a clone of its cntData member.

When inside the lookup method of the Service class I detect the instance of the CounterBag in the set and try to the following:

return counterBag.getCounterData().clone();

the clone() seems not to be visible.

I wonder what needs to be done to make the clone() visible?


Solution

  • Cloneable does not (re)declare the clone method, it's simply inherited from Object. That means instances of T aren't known to have a visible implementation of clone. Define your own subinterface of Cloneable which declares clone and use it as a bound on T. If you can't because you don't have control over the various concrete Ts then you will have to resort to reflection. :(