我在这里提出的问题与 Generic parameters declaration in static member
我发现自己使用原始类型在一个非泛型类中声明了几个成员变量(每个成员都有自己的不同类型),我想知道是否还有其他解决方案。
如果只有一个这样的变量,则可以使该类成为通用类,而无需使用原始类型。取而代之的是,鉴于此类类型的数量可能很多,使类成为泛型会很麻烦。
也可以通过使用通用方法提供此类变量来避免使用原始类型。但是,这将需要在每次调用时创建一个新实例。
以下是说明问题的代码:
import java.util.function.BiFunction;
import java.util.function.Consumer;
public class PreferencesForFruits {
interface Fruit{}
static class Banana implements Fruit {}
static class Apple implements Fruit {}
// a class describing the packaging of a fruit;
// it depends on the type of consumer of the fruit
static class FruitBox<F extends Fruit, C extends Consumer<F>> {
// constructor (note that it doesn't accept wildcards,
// therefore its client must specify fixed types)
FruitBox(F f,C c) {}
}
// preferences for apples and bananas specified in two nested classes:
//
public static class PrefsForApples<AC extends Consumer<Apple>> {
// a functional object specifying
// how to pack a fruit for a customer
BiFunction<Apple,AC,FruitBox<Apple,AC>> packingBiFunction =
(Apple a, AC ac) -> new FruitBox<Apple,AC>(a,ac);
}
//
public static class PrefsForBananas<BS extends Consumer<Banana>> {
// ......
}
// convenience methods to obtained preferences;
// the argument is used here only to fix the generic type of the output
//
static <AC extends Consumer<Apple>>
PrefsForApples<AC> newPrefsForApples(AC appleConsumer) {
return new PrefsForApples<AC>();
}
//
static <BC extends Consumer<Banana>>
PrefsForBananas<BC> newPrefsForBananas(BC bananaSupplierDummy) {
return new PrefsForBananas<BC>();
}
/*
* Now using fields of raw type to avoid creation of distinct instances
*/
// Here are the raw type variables mentioned in the question:
private PrefsForApples prefsForApples;
private PrefsForBananas prefsForBananas;
// the convenience methods convert the raw type
// to the required type
<AC extends Consumer<Apple>>
PrefsForApples<AC> prefsForApplesRaw(AC appleConsumer) {
return (PrefsForApples<AC>) prefsForApples;
}
<BC extends Consumer<Banana>>
PrefsForBananas<BC> prefsForBananasRaw(BC bananaSupplierDummy) {
return (PrefsForBananas<BC>) prefsForBananas;
}