English 中文(简体)
克隆( () 不可可见
原标题:clone() not visible

我有课:

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.

当在 service 类的搜索方法中我检测到集中的 CounterBag 实例,并尝试如下:

return counterBag.getCounterData().clone();

clone () 似乎无法显示 。

我想知道需要做些什么才能使 < code> clone () 可见?

最佳回答

Clooneable 不(re) declare clone 方法, 它只是从 Object 中继承下来的。 这意味着 T 的事例并不为人所知, 无法明显地执行 > cloone 。 定义您自己的 Clooneable 的子界面, 其中宣布了 cloone 并使用它作为约束 < object 。 如果您不能这样做, 因为您无法控制各种混凝土 T , 那么您必须进行反省 。 ()

问题回答

clone 方法在 Object 类中默认定义,是该类中一个 受保护的 成员。

Object 类:

protected native Object clone() throws CloneNotSupportedException;

因此,您必须在您的 < code> CounterBag 类中定义 < code > clone 方法。 那么只有该方法可用 。

public Object clone() throws CloneNotSupportedException {
    return super.clone();
}

您必须将其定义为一种公开的方法, 以便从软件包中提供它 。

确保以 T 类型参数方式通过的类别执行 Cloneable ,并具有适当的可见度,例如:

@Override
public Object clone() {
    try {
        return super.clone();
    } catch (Exception e) {
        // either handle the exception or throw it
        return null;
    }
}

请记住, < a href=> 方法在 protected 类中标记为 protect /code > 类,您需要在自己的类中显示该方法。





相关问题
Spring Properties File

Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...

Logging a global ID in multiple components

I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications. [App A] -> [App B] -> [App C] We set a ...

Java Library Size

If I m given two Java Libraries in Jar format, 1 having no bells and whistles, and the other having lots of them that will mostly go unused.... my question is: How will the larger, mostly unused ...

How to get the Array Class for a given Class in Java?

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....

SQLite , Derby vs file system

I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database. How hard is it to migrate ...