简体   繁体   English

是否可以使用带类型类参数的java注释?

[英]Are java annotations with typed class parameter possible?

Let's supposed i have this interface: 我想我有这个界面:

public interface MyInterface {
   void doStuff();
}

With a concrete implementation: 具体实施:

public class HardCoreConcrete implements MyInterface {
   void doStuff() {
      // i really do stuff, honest
   }
}

And suppose i have this annotation: 假设我有这个注释:

@Target(ElementType.class)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
   Class<MyInterface> clazz;
}

It would be used like this: 它会像这样使用:

@MyAnnotation(clazz = HardCoreConcrete.class)
public class SomeOtherClass {
...
}

Why does this not work? 为什么这不起作用? My compiler complains that for clazz it expected type MyInterface! 我的编译器抱怨,对于clazz,它期望类型MyInterface! But HardCoreConcrete implements MyInterface. 但是HardCoreConcrete实现了MyInterface。

Am I doing something wrong? 难道我做错了什么? Is this not allowed? 这是不允许的? Am i out of luck? 我运气不好吗?

You need 你需要

public @interface MyAnnotation {    
   Class<? extends MyInterface> clazz;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Java泛型。 如何正确扩展扩展通用抽象参数类型的类的参数类型的类 - Java Generics. How to properly extend parameter typed class that extends Generic abstract parameter typed class Java:如何将类型数组类作为参数传递? - Java: How to pass typed-array class as parameter? 如何使用也键入的类型参数创建java.lang.Class? - How to create java.lang.Class with type parameter that is also typed? 如何在Nativescript中使用接口类型的参数调用Java方法(自定义类) - How to call Java method (custom class) with an interface typed parameter in Nativescript Java - 参数注释 - Java - Parameter annotations 带有或不带有参数的Java 6注释重复 - Java 6 Annotations Repeating with or without parameter 是否可以在Java中将类名作为参数传递? - Is it possible to pass class name as a parameter in Java? 是否可以在Java中扩展泛型类参数? - Is it possible to extend a generic class parameter in Java? 在将类型为 class 的属性作为参数传递给方法时,是否可以在没有设置器的情况下访问它? - While passing an attribute typed class as a parameter to a method, is it possible to access it without setters? 如何在Scala中扩展Java类并扩展另一个类的类型化参数? - How to extend a java class extending a typed-parameter of another class in Scala?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM