我试图在某些高级包装器中使用Java接口作为mixin类型D
。使用反射为泛型类型变量生成lambda类
interface WrapsD {
D getWrapped();
}
interface FeatureA extends WrapsD {
default ...
}
interface FeatureB extends WrapsD {
default ...
}
abstract class DWrapperFactory<T extends WrapsD> {
protected T doWrap(D d) {
return() -> d; // <- does not work
}
}
interface FeatureAB extends FeatureA, FeatureB {
}
class ProducingDWithFeatureAB extends DWrapperFactory<FeatureAB> {
protected FeatureAB doWrap(D d) {
return() -> d; // <- has to repeat this
}
}
如图ProducingDWithFeatureAB
看出,doWrap
具有即使身体相同每个子类来实现。 (为什么Java泛型是真正打破再举一个例子。)
既然我已经需要建立像ProducingDWithFeatureAB
其他原因具体类和存在于JRE代码sythesize拉姆达类,应该可以写doWrap
只有一次使用反射。我想知道它是如何做到的。
(doWrap
用于使用匿名内部类实现接口,这更加biolderplate来实现。)
泛型类型是在由于类型擦除编译时间删除。因此,在这种情况下,您所需的通用方法/ lambda可能不可行。 – callyalater
@callyalater我已经必须为每个不同的'T'创建一个子类,因此类型可以通过反射来保证。我只是试图避免一遍又一遍地复制'fun()'的实现,只是为了使类型工作... –
你想要替换的匿名本地类中的代码是什么? – user140547