简体   繁体   English

用Java定义具有相同名称但类型参数数量不同的通用接口

[英]Define generic interfaces with same name but a different number of type parameters in Java

In Java (1.7), is it possible to define multiple interfaces with the same name, but with a different number of type parameters? 在Java(1.7)中,是否可以用相同的名称定义不同类型的参数的多个接口? What I'm essentially looking for is in spirit similar to the Func<TResult> , Func<T1, TResult> , Func<T1, T2, TResult> , Func<T..., TResult> delegate types of .NET. 我本质上在寻找的是本质上类似于.NET的Func<TResult>Func<T1, TResult>Func<T1, T2, TResult>Func<T..., TResult>委托类型的精神。 Very much like optional type parameters . 非常像可选的类型参数

Exists such a functionality in the Java language or am I limited to creating different interfaces with names such as Func0<TResult> , Func1<T1, TResult> , Func2<T1, T2, TResult> ? Java语言中是否存在这样的功能,还是仅限于创建名称不同的接口,例如Func0<TResult>Func1<T1, TResult>Func2<T1, T2, TResult>

Generic types are a compile time feature, this means that at runtime your Func classes would all be the same class. 泛型类型是编译时的功能,这意味着在运行时,您的Func类将都是同一类。 Even if you compiled them individually and added them to your class path, only one would load. 即使您单独编译它们并将它们添加到类路径中,也只会加载它们。 This means they have to have different full class names to be used at runtime. 这意味着它们必须具有不同的完整类名才能在运行时使用。

You can't have a variable number of generic type parameters, but you can "force" a parameter to be ignored by using the Void type for it: 您不能有可变数量的泛型类型参数,但是可以通过使用Void类型来“强制”忽略该参数:

interface Func<T1, T2, IReault> {...}
interface Func1<T1, IResult> extends Func<T1, Void, IResult> {...}
interface Func0<IResult> extends Func<Void, Void, IResult> {...}

Void can't be instantiated, so the only valid Void reference you can pass/return/use is null , thus enforcing that the Void parameter is effectively ignored in both the implementation and the caller. Void无法实例化,因此您可以传递/返回/使用的唯一有效Void引用为null ,从而强制在实现和调用Void有效地忽略Void参数。

Instances of Func1 and Func0 are still instances of Func . Func1Func0的实例仍然是Func实例。

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

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