Java 将动态参数传递给在编译时处理的注释
考虑这个例子,我正在寻找一个解决这类问题的通用方法 我正在开发一个注释处理器,它为类创建接口,基本上复制它们的所有公共方法。可以使用字符串参数配置接口的名称(和包)。但是由于注释是继承的,因此应该能够定义一个将子类的名称映射到其接口名称的Java 将动态参数传递给在编译时处理的注释,java,annotations,annotation-processing,Java,Annotations,Annotation Processing,考虑这个例子,我正在寻找一个解决这类问题的通用方法 我正在开发一个注释处理器,它为类创建接口,基本上复制它们的所有公共方法。可以使用字符串参数配置接口的名称(和包)。但是由于注释是继承的,因此应该能够定义一个将子类的名称映射到其接口名称的接口名称策略 我尝试使用以下动态注释参数 /** *生成包含注释类的所有公共成员方法的接口。 *这只能用于顶级类。 */ @目标({ElementType.TYPE}) @保留(RetentionPolicy.CLASS) @继承的 @记录 公共@接口生成接口{
接口名称策略
我尝试使用以下动态注释参数
/**
*生成包含注释类的所有公共成员方法的接口。
*这只能用于顶级类。
*/
@目标({ElementType.TYPE})
@保留(RetentionPolicy.CLASS)
@继承的
@记录
公共@接口生成接口{
/**
*生成的接口的名称。如果未指定,则{@link#namingStrategy()}
*用于检索接口名称。
*如果名称不是完全限定的,则接口将具有相同的包
*作为注释类。
*/
字符串值()默认为“”;
/**
*返回接口名称的{@link InterfaceNamingStrategy}的实现
*对于给定的注释类。它必须是可访问的,并且包含一个公共的无参数构造函数。
*/
Class@user2393012我不理解你的意思。你能详细说明吗?我重新阅读并误解了问题-忽略:)@user2393012我不理解你的意思。你能详细说明吗?我重新阅读并误解了问题-忽略:)
/**
* Generates an interface that contains all public member mehtods of the annotated class.
* This can only be used on top-level classes.
*/
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.CLASS)
@Inherited
@Documented
public @interface GenerateInterface {
/**
* Name of the generated interface. If this is not specified, the {@link #namingStrategy()}
* is used to retrieve the interface name.
* If the name is not fully qualified, the interface will have the same package
* as the annotated class.
*/
String value() default "";
/**
* An implementation of {@link InterfaceNamingStrategy} that returns the interface name
* for a given annotated class. It must be accessible and contain a public no-arg constructor.
*/
Class<? extends InterfaceNamingStrategy> namingStrategy() default InterfaceNamingStrategy.PrefixI.class;
}
/**
* Naming strategy to be used with {@link GenerateInterface}.
*/
public interface InterfaceNamingStrategy {
/**
* @param impl TypeElement representing the annotated class
* @return the name of the generated interface. See {@link GenerateInterface#value()}.
*/
String getInterfaceName(TypeElement impl);
/**
* Will create the interface {@code Foo} for the annotated class {@code FooImpl}
*/
public static class ExceptLastFourChars implements InterfaceNamingStrategy {
@Override
public String getInterfaceName(TypeElement impl) {
return impl.getSimpleName().toString().substring(0, impl.getSimpleName().length()-4);
}
}
/**
* Will create the interface {@code IFoo} for the annotated class {@code Foo}
*/
public static class PrefixI implements InterfaceNamingStrategy {
@Override
public String getInterfaceName(TypeElement impl) {
return "I" + impl.getSimpleName();
}
}
}