Home > Mobile >  What is the right way to assign a data member to another data member of generic type
What is the right way to assign a data member to another data member of generic type

Time:10-30

interface IBase {
    void doJob();
}

public class MyCache<T extends IBase> {
    private T t1;
    private T t2;
    public MyCache(T t1, T t2) {
        this.t1 = t1;
        this.t2 = t2;
    }

    @PostConstruct
    private void init() {
        t1.update();
        t2 = t1.clone(); // ERROR!
    }
}

As you see, I'm trying to develop a generic class. In the function init(), I assign the copy of t1 to t2. But it can't be compiled.

I'm not very good at Java. Can someone help me on this issue?

CodePudding user response:

Look at the contract public Object clone(), so to use this method in your class you shouild declare it and case Object to the T.

interface IBase extends Cloneable {

    void doJob();

    void update();
    
    Object clone();

}

public class MyCache<T extends IBase> {

    private T t1;
    private T t2;

    public MyCache(T t1, T t2) {
        this.t1 = t1;
        this.t2 = t2;
    }

    private void init() {
        t1.update();
        t2 = (T)t1.clone();
    }
}

P.S. This is working solution, but at this time an outdated. It's better to use a copy constructor instead.

  • Related