首页 > 解决方案 > 反射是否反映Java中的继承?

问题描述

在 Java 中,我有一个映射,其中键是 Class<BaseType> 对象。每个条目都以 Class<ExtendedType> 的对象为键,其中 ExtendedType 扩展了 BaseType。(有许多不同的 ExtendedType 类,比如 ExtendedType1、ExtendedType2 等,只有一个 BaseType。)

Map<Class<BaseType>, String> myMap;

我知道它适用于我们的项目。但是,我想知道这在语法上是否正确?

如果语法没问题,那么以下内容也应该没问题(除了两行 - 请参阅代码中的注释):

class A {
}

class B extends A {
}

public static void main(String[] args) {

  // First inheritance:

  A a = new A();
  // Do something with a.

  B b = new B();
  // Do something with b.

  a = new B();
  // Should be fine since B extends A.

  b = new A();
  // Should NOT compile. A is a superclass of B.


  // Now reflection:

  Class<A> classA = A.class;
  // Do something with classA.

  Class<B> classB = B.class;
  // Do something with classB.

  classA = B.class;
  // Should be fine since Class<B> extends Class<A>. Does it really?

  classB = A.class;
  // Should NOT compile. Class<A> is a superclass of Class<B>. Is it?

}

你怎么看?感谢您的任何提示/评论。

标签: javainheritancereflection

解决方案


推荐阅读