Java 如何使用具有泛型的接口创建注释?
我正在尝试创建一个注释,该注释允许我用所提供类的实例包装Springbean。接口有一个类型参数,如果可能的话,它不应该由包装类指定。请参阅下面的代码以了解我的意思 我成功地获得了一个编译,但还没有尝试通过使MyWrapperImpl使用MyWrappedClass使用的类的super类实现类型参数来修复运行时,但是我宁愿不指定它 如何保留类型参数?换句话说,我怎样才能使MyWrapperImpl尽可能通用 注释:Java 如何使用具有泛型的接口创建注释?,java,spring,annotations,Java,Spring,Annotations,我正在尝试创建一个注释,该注释允许我用所提供类的实例包装Springbean。接口有一个类型参数,如果可能的话,它不应该由包装类指定。请参阅下面的代码以了解我的意思 我成功地获得了一个编译,但还没有尝试通过使MyWrapperImpl使用MyWrappedClass使用的类的super类实现类型参数来修复运行时,但是我宁愿不指定它 如何保留类型参数?换句话说,我怎样才能使MyWrapperImpl尽可能通用 注释: @Documented @Target(ElementType.TYPE) @I
@Documented
@Target(ElementType.TYPE)
@Inherited
@Retention(RetentionPolicy.Runtime)
public @interface Wrap {
Class<? extends MyInterface<?>> classToWrapWith();
}
我不明白你想做什么。请澄清。@SotiriosDelimanolis我将代码更改为更具描述性的名称。希望这有帮助?如果没有,你有具体的建议我可以改进什么?
public interface MyInterface<T> {
T getSomething();
}
public class MyWrapperImpl<T> implements MyInterface<T> {
private MyInterface<T> wrapped;
public T getSometing() {
// Do something special, such as:
System.out.println("Calling get something from wrapped object");
return wrapped.getSomething(); // MyWrapperImpl should "use" the type from the wrapped instance.
}
}
// Attempt 1
@Wrap(classToWrapWith = MyWrapperImpl.class) // <-- Compile error "found class<MyWrapperImpl>, required class<? extends MyInterface<?>>"
// Attempt 2
@Wrap(classToWrapWith = MyWrapperImpl<T>.class) // <-- Compile error, cannot select from parameterized type.
public class MyWrappedClass implements MyInterface<SubObject> {
public SubObject getSomething() {
return new SubObject();
}
}
public class MyWrapperImpl<SuperObject> implements MyInterface<T> {
private MyInterface<SuperObject> wrapped;
public SuperObject getSometing() {
return wrapped.getSomething();
}
}