【问题标题】:Generics issue: clone() attempting to assign weaker access privileges泛型问题:clone() 试图分配较弱的访问权限
【发布时间】:2015-10-20 09:42:21
【问题描述】:

让我们有这样的类结构:

public interface TypeIdentifiable {}

public interface TypeCloneable extends Cloneable {
  public Object clone() throws CloneNotSupportedException;
}

public class Foo implements TypeCloneable, TypeIdentifiable {

   @Override
   public Object clone() throws CloneNotSupportedException {
      // ...
      return null;
   }
}

public abstract class AbstractClass<T extends TypeCloneable & TypeIdentifiable> {

   public void foo(T element) throws Exception {
      TypeCloneable cloned = (TypeCloneable) element.clone();
      System.out.println(cloned);
   }
}

我有这个编译错误(尽管 IDE,在我的例子中是 Intellij,在编码时无法显示错误)

Error:(4, 37) java: clone() in java.lang.Object cannot implement clone() in foo.TypeCloneable attempting to assign weaker access privileges; was public

我知道编译器试图从Object 而不是TypeCloneable 调用clone() 方法,但我不明白为什么。我还尝试将它转换为 TypeCloneable(我假设编译器会知道在这种情况下调用哪个 clone() 方法,但同样的问题)。

   public void foo(T element) throws Exception {
      TypeCloneable typeCloneable = (TypeCloneable) element;
      TypeCloneable cloned = (TypeCloneable) typeCloneable.clone();
   }

我有点困惑...我可以在这里做些什么来强制从 TypeCloneable 调用 clone() 吗?

谢谢你的帮助

【问题讨论】:

  • 如果我正确理解 JLS,这应该可以编译。我认为这是一个错误。 stackoverflow.com/questions/33023332/…
  • 所以是的...这似乎是一个错误。我没有找到这个问题。谢谢!

标签: java generics intellij-idea compiler-errors clone


【解决方案1】:

这对我有用,(我猜这是类型和类型上限语法的问题):

interface TypeIdentifiable {}

interface TypeCloneable extends Cloneable {
  public Object clone() throws CloneNotSupportedException;
}

class Foo implements TypeCloneable, TypeIdentifiable {

   @Override
   public Object clone() throws CloneNotSupportedException {
      // ...
      return null;
   }
}

interface TypeCloneableAndIndetifiable extends TypeCloneable, TypeIdentifiable  {

}
abstract class AbstractClass<T extends TypeCloneableAndIndetifiable> {

   public void foo(T element) throws Exception {
      TypeCloneable cloned = (TypeCloneable) element.clone();
      System.out.println(cloned);
   }
}

【讨论】:

  • 感谢您回答@WillShackleford。是的,如果我将两个接口包装成一个,就像你说的那样,它可以工作。问题是 TypeCloneable 和 TypeIdentifiable 都是遗留代码。你认为这可能是 & 类型上限语法的错误吗?
  • 我不确定。在我看到这个问题之前,我会认为它会像你使用它一样工作。
  • 正如@Paul Boddington 在评论中指出的那样,这似乎是一个错误。也许你可以编辑你的答案添加这个。无论如何,我接受您关于将两个接口封装为一个的建议。谢谢
猜你喜欢
  • 2012-07-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-07-22
  • 1970-01-01
  • 2019-12-31
相关资源
最近更新 更多