Define generic interfaces with the same name but with 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 am basically looking for in spirit similar to the types of delegates Func<TResult>

, Func<T1, TResult>

, Func<T1, T2, TResult>

, Func<T..., TResult>

. Much like optional type parameters.

There is such a functionality in the Java language, or I'm limited to creating different interfaces with names such as Func0<TResult>

, Func1<T1, TResult>

, Func2<T1, T2, TResult>

?

+3


source to share


2 answers


Generic types are a compile-time feature, which means your classes Func

will be the same at runtime . Even if you compiled them separately and added them to your classpath, only one will load. This means that they must have different fully qualified class names to be used at runtime.



+2


source


You cannot have a variable number of generic type parameters, but you can "force" ignore a parameter by using the type Void

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

cannot be created, so the only valid reference Void

you can pass / return / use is null

, thereby ensuring that the parameter is Void

effectively ignored in both the implementation and the caller.

Instances Func1

and Func0

are still instances Func

.

0


source







All Articles