相关疑难解决方法(0)

具有继承和泛型的流畅API

我正在编写一个流畅的API来配置和实例化一系列"消息"对象.我有一个消息类型的层次结构.

为了能够在使用流畅的API时访问子类的方法,我使用泛型来参数化子类,并使所有流畅的方法(以"with"开头)返回泛型类型.请注意,我省略了流体方法的大部分主体; 其中有很多配置.

public abstract class Message<T extends Message<T>> {

    protected Message() {

    }

    public T withID(String id) {
        return (T) this;
    }
}
Run Code Online (Sandbox Code Playgroud)

具体子类同样重新定义泛型类型.

public class CommandMessage<T extends CommandMessage<T>> extends Message<CommandMessage<T>> {

    protected CommandMessage() {
        super();
    }

    public static CommandMessage newMessage() {
        return new CommandMessage();
    }

    public T withCommand(String command) {
        return (T) this;
    }
}

public class CommandWithParamsMessage extends
    CommandMessage<CommandWithParamsMessage> {

    public static CommandWithParamsMessage newMessage() {
        return new CommandWithParamsMessage();
    }

    public CommandWithParamsMessage withParameter(String paramName,
        String paramValue) {
        contents.put(paramName, …
Run Code Online (Sandbox Code Playgroud)

java generics fluent-interface

31
推荐指数
3
解决办法
8671
查看次数

继承方法返回引用类型

我正面临这个问题中描述的问题,但想找到一个没有所有演员和@SuppressWarning注释的解决方案(如果可能的话).

一个更好的解决方案是建立在引用的解决方案之上:

  • 删除@SuppressWarning
  • 删除演员

此处提供的解决方案将根据标准评分为2分.Bounty用大多数积分去解决方案,或者如果有多个积分,那么"最优雅的"积分将达到2分.

java generics inheritance

8
推荐指数
2
解决办法
371
查看次数

子调用C#面向对象返回类型"this"

我有2个类,每个类在所有函数中返回自己:

public class Parent{
   public Parent SetId(string id){
      ...
      return this
   }
}

public class Child : Parent{
   public Child SetName(string id){
      ...
      return this
   }
}
Run Code Online (Sandbox Code Playgroud)

我想启用这种API:

new Child().SetId("id").SetName("name");
Run Code Online (Sandbox Code Playgroud)

SetName因为无法访问SetId的回报Parent,并SetName为上Child.

怎么样?

c# oop parent-child

4
推荐指数
1
解决办法
634
查看次数

标签 统计

generics ×2

java ×2

c# ×1

fluent-interface ×1

inheritance ×1

oop ×1

parent-child ×1