Java创建一个实现另一个带约束的泛型接口的泛型类。

huangapple go评论93阅读模式
英文:

Java creating a generic class that implement another generic interface with constraints

问题

界面要实现的部分:

public interface Message {
}

public interface Handles<T extends Message> {
    void handle(T message);
}

具体实现部分:

public class EnforcementHandler<T extends Handles<T extends Message>> {
}

意外的限制

在Java中是否可能出现这种模式?

英文:

Interface to be implemented:

public interface Message {
}

public interface Handles&lt;T extends Message&gt;  {
    void hanlde(T message);
}

Concrete implementation:

public class EnforcementHandler&lt;T extends Handles&lt;T extends Message&gt;&gt; {

}

Unexpected bound

Is this pattern possible in Java?

答案1

得分: 4

你必须将它写成 EnforcementHandler<M extends Message, T extends Handles<M>>

英文:

You must write it as EnforcementHandler&lt;M extends Message, T extends Handles&lt;M&gt;&gt;.

答案2

得分: 0

你的EnforcementHandler的确切责任是模糊的。根据其名称中的“Handler”部分,我认为它的责任是“处理”事务。所以,根据我理解,这似乎是一个适当的实现。

public class EnforcementHandler<M extends Message> implements Handler<M> {

    public void handle(M msg) {
        out.printf("%1$70s%n ", msg.read());
    }
}

此演示展示了如何使用它

...
Message msg = () -> "Friends of space, how are you all? Have you eaten yet? Come visit us if you have time.";

EnforcementHandler handler = new EnforcementHandler<>();

handler.handle(msg);
...

将这条友好消息打印到stdout。友好消息如下:

Friends of space, how are you all? Have you eaten yet? Come visit us if you have time.
英文:

What the exact responsibility of your EnforcementHandler is, is ambiguous.

Going by the „Handler“ part of its name, suggests to me that its responsibility is to „handle“ things. So this seems an appropriate implementation to my understanding&hellip;

public class EnforcementHandler&lt;M extends Message&gt; implements Handler&lt;M&gt;{ 
    
    public void handle( M msg ) { out.printf( &quot;%1$70s%n &quot;, msg.read( ) ); }
}

This demo shows how it could be used&hellip;

  ...
  Message msg = ( ) -&gt; &quot;Friends of space, how are you all? Have you eaten yet? Come visit us if you have time.&quot;;
  
  EnforcementHandler&lt; Message &gt; handler = new EnforcementHandler&lt; &gt;( );
  
  handler.handle( msg );
  ...

&hellip;Printing this friendly message to stdout&hellip;

Friends of space, how are you all? Have you eaten yet? Come visit us if you have time.

huangapple
  • 本文由 发表于 2020年8月8日 05:34:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/63309418.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定