java - 如何在 Java 中使用 @inherited 注解?

标签 java inheritance annotations

我没有在 Java 中获得 @Inherited 注释。如果它自动为您继承方法,那么如果我需要以自己的方式实现该方法,那又如何呢?

它将如何知道我的实现方式?

另外据说如果我不想使用它,而是以老式的 Java 方式来做,我必须实现 equals()toString()Object类的hashCode()方法,以及java.lang.annotation.Annotation类的注解类型方法.

这是为什么呢?

即使我不知道 @Inherited 注释和过去也可以正常工作的程序,我也从未实现过这些。

请有人从头开始解释一下。

最佳答案

只是没有误解:您确实询问了java.lang.annotation.Inherited .这是注解的注解。表示被注解的类的子类被认为与它们的父类(super class)具有相同的注解。

示例

考虑以下 2 个注释:

@Inherited
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface InheritedAnnotationType {
    
}

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface UninheritedAnnotationType {
    
}

如果三个类是这样注释的:

@UninheritedAnnotationType
class A {
    
}

@InheritedAnnotationType
class B extends A {
    
}

class C extends B {
    
}

运行此代码

System.out.println(new A().getClass().getAnnotation(InheritedAnnotationType.class));
System.out.println(new B().getClass().getAnnotation(InheritedAnnotationType.class));
System.out.println(new C().getClass().getAnnotation(InheritedAnnotationType.class));
System.out.println("_________________________________");
System.out.println(new A().getClass().getAnnotation(UninheritedAnnotationType.class));
System.out.println(new B().getClass().getAnnotation(UninheritedAnnotationType.class));
System.out.println(new C().getClass().getAnnotation(UninheritedAnnotationType.class));

会打印出类似这样的结果(取决于注解的包):

null
@InheritedAnnotationType()
@InheritedAnnotationType()
_________________________________
@UninheritedAnnotationType()
null
null

如您所见,UninheritedAnnotationType 没有被继承,但 CB 继承注释 InheritedAnnotationType

我不知道这与什么方法有关。

关于java - 如何在 Java 中使用 @inherited 注解?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23973107/

相关文章:

Java hibernate如何使用注解映射继承

java - 如何在我的界面中为最终变量创建 Java 字段注释

java - 在 Akka Http 中发送大量对象列表

java - 主类执行后输出不同

java - 陈述 。 executeUpdate 给出第 1 行 X 列截断的日期错误

java - 使用Gson以自定义方式将Date对象序列化为JSON(注释)

java - 我可以在构造函数中传递多个 Super 调用吗?

C++继承与多态

java - JUnit 测试时排除@Component 类的过滤器?

java - org.springframework.beans.factory.annotation.Value 的替代方案,它不是基于 Spring 的