【发布时间】:2017-07-08 01:55:50
【问题描述】:
假设我有一个 Java 接口:
public interface IMyInterface {
void hello(String who);
}
我想使用 Xtend 创建一个活动注释,它会自动(并且通常)为 Xtend 类实现该接口。所以,当我写的时候
@InterfaceImplementor
class MyInterfaceImplementation implements IMyInterface {
}
我希望 Xtend 生成
@InterfaceImplementor
@SuppressWarnings("all")
public class MyInterfaceImplementation implements IMyInterface {
public void hello(final String who) {
delegate.hello(who);
}
}
我到此为止:
@Active(typeof(ImplementationGenerator))
annotation InterfaceImplementor{}
class ImplementationGenerator implements TransformationParticipant<MutableClassDeclaration> {
override doTransform(List<? extends MutableClassDeclaration> annotatedTargetElements, extension TransformationContext context)
{
for(element : annotatedTargetElements)
{
for(method : element.declaredMethods)
{
implementMethod(element, method, context)
}
}
}
def implementMethod(MutableClassDeclaration clazz, MutableMethodDeclaration method, extension TransformationContext context)
{
method.body = ['''delegate.«method.simpleName»(«method.callParameters»);''']
}
def callParameters(MutableMethodDeclaration method)
{
method.parameters.map[ simpleName ].join(', ')
}
}
只要我覆盖目标类中的每个方法,它就可以工作:
@InterfaceImplementor
class MyInterfaceImplementation implements IMyInterface {
override hello(String who) {}
}
但是,我实际上希望 Xtend 生成整个类主体,而不必手动声明每个方法。为此,我尝试在活动注释中使用element.implementedInterfaces,但这些只是TypeReferences,我不知道如何从类型引用中获取声明的方法。所以这就是我卡住的地方。
在活动注释评估期间甚至可以解决TypeReference 吗?还有其他方法可以实现我的目标吗?
【问题讨论】:
标签: java code-generation xtend