如何使用具有泛型的接口创建注释?

时间:2015-11-04 15:56:03

标签: java spring annotations

我正在尝试创建一个注释,允许我用提供的类的实例包装一个(spring)bean。该接口有一个类型参数,该类型参数(如果可能的话,不应该)由包装类指定。请参阅下面的代码,了解我的意思。

我设法通过MyWrapperImpl使用MyWrappedClass使用的类的超类实现type参数来获得(编译,还没有尝试过运行时)修复,但我宁愿不指定它。

如何保留类型参数?换句话说,如何让MyWrapperImpl尽可能保持通用?

注释:

@Documented
@Target(ElementType.TYPE)
@Inherited
@Retention(RetentionPolicy.Runtime)
public @interface Wrap {
    Class<? extends MyInterface<?>> classToWrapWith();
}

接口:

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();
    }
}

包含工作修补程序的包装器类(其中SuperObjectSubObject的父类,在MyWrappedClass中使用(见上文)):

public class MyWrapperImpl<SuperObject> implements MyInterface<T> {
    private MyInterface<SuperObject> wrapped;

    public SuperObject getSometing() {
        return wrapped.getSomething();
    }
}

0 个答案:

没有答案