有没有办法用类型变量引用当前类型? [英] Is there a way to refer to the current type with a type variable?

查看:38
本文介绍了有没有办法用类型变量引用当前类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我正在尝试编写一个函数来返回当前类型的实例.有没有办法让 T 引用确切的子类型(所以 T 应该引用 B 类中的 B)?

Suppose I'm trying to write a function to return an instance of the current type. Is there a way to make T refer to the exact subtype (so T should refer to B in class B)?

class A {
    <T extends A> foo();
}

class B extends A {
    @Override
    T foo();
}

推荐答案

基于 StriplingWarrior 的回答,我认为以下模式是必要的(这是分层流畅构建器 API 的秘诀).

To build on StriplingWarrior's answer, I think the following pattern would be necessary (this is a recipe for a hierarchical fluent builder API).

解决方案

首先是一个基础抽象类(或接口),它制定了返回扩展类的实例的运行时类型的契约:

First, a base abstract class (or interface) that lays out the contract for returning the runtime type of an instance extending the class:

/**
 * @param <SELF> The runtime type of the implementor.
 */
abstract class SelfTyped<SELF extends SelfTyped<SELF>> {

   /**
    * @return This instance.
    */
   abstract SELF self();
}

所有中间扩展类必须是abstract并保持递归类型参数SELF:

All intermediate extending classes must be abstract and maintain the recursive type parameter SELF:

public abstract class MyBaseClass<SELF extends MyBaseClass<SELF>>
extends SelfTyped<SELF> {

    MyBaseClass() { }

    public SELF baseMethod() {

        //logic

        return self();
    }
}

其他派生类可以以相同的方式进行.但是,这些类中没有一个可以直接用作变量类型而不使用原始类型或通配符(这违背了模式的目的).例如(如果 MyClass 不是 abstract):

Further derived classes can follow in the same manner. But, none of these classes can be used directly as types of variables without resorting to rawtypes or wildcards (which defeats the purpose of the pattern). For example (if MyClass wasn't abstract):

//wrong: raw type warning
MyBaseClass mbc = new MyBaseClass().baseMethod();

//wrong: type argument is not within the bounds of SELF
MyBaseClass<MyBaseClass> mbc2 = new MyBaseClass<MyBaseClass>().baseMethod();

//wrong: no way to correctly declare the type, as its parameter is recursive!
MyBaseClass<MyBaseClass<MyBaseClass>> mbc3 =
        new MyBaseClass<MyBaseClass<MyBaseClass>>().baseMethod();

这就是我将这些类称为中级"的原因,也是它们都应该被标记为抽象的原因.为了关闭循环并利用模式,叶子"类是必要的,它用自己的类型解析继承的类型参数SELF并实现self().它们还应该被标记为 final 以避免破坏合同:

This is the reason I refer to these classes as "intermediate", and it's why they should all be marked abstract. In order to close the loop and make use of the pattern, "leaf" classes are necessary, which resolve the inherited type parameter SELF with its own type and implement self(). They should also be marked final to avoid breaking the contract:

public final class MyLeafClass extends MyBaseClass<MyLeafClass> {

    @Override
    MyLeafClass self() {
        return this;
    }

    public MyLeafClass leafMethod() {

        //logic

        return self(); //could also just return this
    }
}

这样的类使模式可用:

MyLeafClass mlc = new MyLeafClass().baseMethod().leafMethod();
AnotherLeafClass alc = new AnotherLeafClass().baseMethod().anotherLeafMethod();

这里的价值是方法调用可以在类层次结构中上下链接,同时保持相同的特定返回类型.

The value here being that method calls can be chained up and down the class hierarchy while keeping the same specific return type.

免责声明

以上是 Java 中奇妙重复模板模式的实现.这种模式本质上不是安全的,应仅用于内部 API 的内部工作.原因是无法保证上述示例中的类型参数 SELF 实际上会解析为正确的运行时类型.例如:

The above is an implementation of the curiously recurring template pattern in Java. This pattern is not inherently safe and should be reserved for the inner workings of one's internal API only. The reason is that there is no guarantee the type parameter SELF in the above examples will actually be resolved to the correct runtime type. For example:

public final class EvilLeafClass extends MyBaseClass<AnotherLeafClass> {

    @Override
    AnotherLeafClass self() {
        return getSomeOtherInstanceFromWhoKnowsWhere();
    }
}

这个例子暴露了模式中的两个洞:

This example exposes two holes in the pattern:

  1. EvilLeafClass 可以撒谎"并用任何其他扩展 MyBaseClass 的类型替换 SELF.
  2. 与此无关,不能保证 self() 会实际返回 this,这可能是也可能不是问题,具体取决于基中状态的使用逻辑.
  1. EvilLeafClass can "lie" and substitute any other type extending MyBaseClass for SELF.
  2. Independent of that, there's no guarantee self() will actually return this, which may or may not be an issue, depending on the use of state in the base logic.

由于这些原因,这种模式很有可能被误用或滥用.为了防止这种情况发生,允许none 所涉及的类被公开扩展 - 注意我在 MyBaseClass 中使用包私有构造函数,它取代了隐式公共构造函数:

For these reasons, this pattern has great potential to be misused or abused. To prevent that, allow none of the classes involved to be publicly extended - notice my use of the package-private constructor in MyBaseClass, which replaces the implicit public constructor:

MyBaseClass() { }

如果可能,也将 self() 包保持为私有,这样就不会给公共 API 增加噪音和混乱.不幸的是,这只有在 SelfTyped 是一个抽象类时才有可能,因为接口方法是隐式公开的.

If possible, keep self() package-private too, so it doesn't add noise and confusion to the public API. Unfortunately this is only possible if SelfTyped is an abstract class, since interface methods are implicitly public.

作为zhong.j.yu 在评论中指出SELF 上的限制可能会被简单地删除,因为它最终无法确保自我类型":

As zhong.j.yu points out in the comments, the bound on SELF might simply be removed, since it ultimately fails to ensure the "self type":

abstract class SelfTyped<SELF> {

   abstract SELF self();
}

Yu 建议只依赖合约,避免因不直观的递归边界而产生任何混淆或错误的安全感.就我个人而言,我更喜欢离开这个界限,因为 SELF extends SelfTyped 代表了 Java 中 self 类型的最接近可能的表达.但于的意见绝对符合 可比.

Yu advises to rely only on the contract, and avoid any confusion or false sense of security that comes from the unintuitive recursive bound. Personally, I prefer to leave the bound since SELF extends SelfTyped<SELF> represents the closest possible expression of the self type in Java. But Yu's opinion definitely lines up with the precedent set by Comparable.

结论

这是一个有价值的模式,它允许对您的构建器 API 进行流畅且富有表现力的调用.我在认真的工作中使用过它几次,最显着的是编写一个自定义查询构建器框架,它允许像这样的调用站点:

This is a worthy pattern that allows for fluent and expressive calls to your builder API. I've used it a handful of times in serious work, most notably to write a custom query builder framework, which allowed call sites like this:

List<Foo> foos = QueryBuilder.make(context, Foo.class)
    .where()
        .equals(DBPaths.from_Foo().to_FooParent().endAt_FooParentId(), parentId)
        .or()
            .lessThanOrEqual(DBPaths.from_Foo().endAt_StartDate(), now)
            .isNull(DBPaths.from_Foo().endAt_PublishedDate())
            .or()
                .greaterThan(DBPaths.from_Foo().endAt_EndDate(), now)
            .endOr()
            .or()
                .isNull(DBPaths.from_Foo().endAt_EndDate())
            .endOr()
        .endOr()
        .or()
            .lessThanOrEqual(DBPaths.from_Foo().endAt_EndDate(), now)
            .isNull(DBPaths.from_Foo().endAt_ExpiredDate())
        .endOr()
    .endWhere()
    .havingEvery()
        .equals(DBPaths.from_Foo().to_FooChild().endAt_FooChildId(), childId)
    .endHaving()
    .orderBy(DBPaths.from_Foo().endAt_ExpiredDate(), true)
    .limit(50)
    .offset(5)
    .getResults();

关键在于 QueryBuilder 不仅仅是一个平面实现,而是从构建器类的复杂层次结构扩展的叶子".WhereHavingOr 等助手使用了相同的模式,所有这些都需要共享重要的代码.

The key point being that QueryBuilder wasn't just a flat implementation, but the "leaf" extending from a complex hierarchy of builder classes. The same pattern was used for the helpers like Where, Having, Or, etc. all of which needed to share significant code.

但是,您不应忽视这样一个事实,即所有这些最终都只是语法糖.一些有经验的程序员对 CRT 模式采取强硬立场,或者至少是 对其好处与增加的复杂性进行权衡持怀疑态度.他们的担忧是合理的.

However, you shouldn't lose sight of the fact that all this only amounts to syntactic sugar in the end. Some experienced programmers take a hard stance against the CRT pattern, or at least are skeptical of the its benefits weighed against the added complexity. Their concerns are legitimate.

归根结底,在实施之前仔细看看它是否真的有必要——如果有,不要让它公开扩展.

Bottom-line, take a hard look at whether it's really necessary before implementing it - and if you do, don't make it publicly extendable.

这篇关于有没有办法用类型变量引用当前类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆