【问题标题】:NoSuchFieldError when extending Interface in generic class在泛型类中扩展接口时出现 NoSuchFieldError
【发布时间】:2014-08-22 03:35:56
【问题描述】:

我有一个 bean ArtistEntityBean 扩展 GenericEntityBean

public class ArtistEntityBean extends GenericEntityBean<Artist> {

    public ArtistEntityBean() {
        item = new Artist();
    }

}

-

public abstract class GenericEntityBean<T extends IntEntity> implements Serializable {

    protected T item;

    public void init(Integer id){
        item.setId(id);
    }
}

-

public class Artist extends ArtistBaseEntity implements Comparable<Artist> {

...

}

-

public abstract class ArtistBaseEntity implements IntEntity {

...

}

-

public interface IntEntity {

    Integer getId();

    void setId(Integer id);
}

-

我试图在GenericEntityBean 类中放置尽可能多的代码,这就是为什么我想到使用接口以便能够设置itemid

这并不难,因为我在ArtistEntityBean 的构造函数中得到了一个NoSuchFieldError,我不知道为什么?

【问题讨论】:

  • GenericEntityBean 如何知道项目?它是一个父类
  • 您在GenericEntityBean 中有item 字段吗?
  • NoSuchFieldError 是运行时异常,通常仅在您以某种方式弄乱类路径时才会发生(例如,在运行时使用旧版本的 .class)。

标签: java generics types interface


【解决方案1】:

如果itempublicprotected 或默认你必须使用

super.item = new Artist();

ArtistEntityBean的构造函数中。

如果是private,则必须在抽象类中提供setter方法。


编辑:如果您没有在抽象类中指定item,请执行以下操作

public abstract class GenericEntityBean<T extends IntEntity> implements Serializable {

    protected T item;

    public void init(Integer id){
        item.setId(id);
    }
}

【讨论】:

  • 谢谢!它在使用super.item = new Artist(); 时有效。我认为不需要它,因为 item 是继承的。
猜你喜欢
  • 1970-01-01
  • 2015-04-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-09
  • 2021-11-07
  • 2021-10-09
  • 1970-01-01
  • 2020-07-19
相关资源
最近更新 更多