【问题标题】:Understanding Generics了解泛型
【发布时间】:2010-12-30 23:51:35
【问题描述】:
    @Entity
    @Table(name = "your_entity")
    public class YourEntityClass implements IEntity<Long> {

        @Id
        @SequenceGenerator(name = "gen_test_entity2_id", sequenceName = "test_entity2_id_seq", allocationSize = 10)
        @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "gen_test_entity2_id")
        private Long id;

        @Column(name = "name", nullable = false, length = 64)
        private String name;

        /*
         * Create constructors, getters, setters, isEquals, hashcode, etc.
         */
    }

public interface IEntity<I extends Serializable> extends Serializable {

    /**
     * Property which represents id.
     */
    String P_ID = "id";

    /**
     * Get primary key.
     *
     * @return primary key
     */
    I getId();

    /**
     * Set primary key.
     *
     * @param id primary key
     */
    void setId(I id);
}

对于上面的代码,我的问题是,为什么YourEntityClass需要在IEntity&lt;Long&gt;中传递Long?为什么不用IEntity&lt;String&gt; 之类的东西呢?是不是因为id 的类型是Long,而id 的getter 必须返回我们提供给IEntity 的相同类型?

【问题讨论】:

    标签: java generics implementation


    【解决方案1】:

    YourEntityClass&lt;Long&gt; 任意放入IEntity。任何实现Serializable 的类型都可以去那里。

    选择I 的类型后,getId() 方法必须返回相同的类型。

    例如,您可以有另一个实现IEntity&lt;String&gt;getId() 的类,在这种情况下必须返回String

    【讨论】:

      【解决方案2】:

      YourEntityClass 正在实现一个泛型接口,它正在为泛型接口指定特定类型。它有一个使用特定类型(Long)的方法,因为这是实现该接口所需要的。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-11-30
        • 2012-03-15
        • 2020-08-14
        • 1970-01-01
        • 2021-12-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多