简体   繁体   English

在接口中使用Java泛型

[英]Using Java generics in interfaces

I'd like to create an interface that has the following methods: 我想创建一个具有以下方法的接口:

public interface MyInterface {
  public Class<X> getClass();
  public void handle(X message);
}

Where X has to be the same type in both methods. 其中X必须在两种方法中都是相同的类型。 The reason I need to do this is I'm getting messages that are blobs that need to be casted into the appropriate class (using getClass) and then I'd like to force implementers to implement a handle method that takes the appropriate class (instead of assuming there is one and using reflection to call it). 我需要这样做的原因是我得到的消息是blob需要被转换到适当的类(使用getClass)然后我想强制实现者实现一个带有适当类的handle方法(而不是假设有一个并使用反射来调用它)。

It seems like the only way to do this is to add a type param to the interface like so: 看起来这样做的唯一方法是在接口中添加一个类型参数,如下所示:

public interface MyInterface<T> {
...
}

but that is less than ideal because of cascading dependencies that would require specifying that type in various other classes. 但这不太理想,因为需要在各种其他类中指定该类型的级联依赖。 Any suggestions? 有什么建议? Thanks! 谢谢!

Where X has to be the same type in both methods 其中X必须在两种方法中都是相同的类型

You can not enforce 2 methods of an interface to depend one another just by the definition. 您不能仅通过定义强制接口的两个方法相互依赖。
getClass and handle will always be 2 separate methods. getClasshandle将始终是2个单独的方法。
What you perhaps should be doing is have 1 method, the handle and pass as a parameter a type of the class (could be something as simple as an Enum or any indicator) and delegate to a Factory to create the appropriate class to be used inside the handle method. 您可能应该做的是有1个方法, handle和传递作为参数类的类 (可以像Enum或任何指标一样简单)并委托给Factory来创建适当的类来在里面使用handle方法。
So handle method would (eventually) get the appropriate class to work with. 因此handle方法将(最终)获得适当的类来使用。

You can specify generic type parameters for methods, like so: 您可以为方法指定泛型类型参数,如下所示:

public <X> void handle(X message);

But this won't ensure consistency across methods, so if you have: 但是这不能确保方法之间的一致性,所以如果你有:

public <X> Class<X> getClazz();
public <X> void handle(X message);

You can't say that the <X> is the same for both methods. 你不能说两种方法的<X>都是一样的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM