简体   繁体   中英

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? 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. 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> ?

Generic types are a compile time feature, this means that at runtime your Func classes would all be the same class. 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:

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.

Instances of Func1 and Func0 are still instances of Func .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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