我在Java语言中没有得到@Inherited注解。如果它自动为您继承方法,那么如果我需要以自己的方式实现该方法,那该怎么办呢?
它如何知道我的实现方式?
另外,据说如果我不想使用它,而是以一种老式的Java方式来实现,我必须实现Object类的equals()、toString()和hashCode()方法,以及java.lang.annotation.Annotation类的注释类型方法。
为什么会这样呢?
我从来没有实现过这些,即使我不知道@Inherited注解,程序也可以很好地工作。
请有人从头给我解释一下这件事。
发布于 2014-06-01 01:42:36
只是没有误解:你确实问了关于java.lang.annotation.Inherited的问题。这是annotations.It的一个注解,这意味着带注解的类的子类被认为具有与其超类相同的注解。
示例
考虑以下两个注释:
@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不是继承的,但是C从B继承了注释InheritedAnnotationType。
我不知道有什么方法可以解决这个问题。
https://stackoverflow.com/questions/23973107
复制相似问题