简体   繁体   English

Java继承,泛型和字节码

[英]Java inheritance, generics and the byte-code

When a class in Java inherits another, does the inherited class become (physically) part of the inheriting class such that its byte-code is added to the .class file for the inheriting class? 当Java中的一个类继承另一个类时,继承的类是否(在物理上)成为继承类的一部分,从而将其字节代码添加到该继承类的.class文件中? Or does the .class file for the inheriting class contain only the part specific to it and it's at run time that object details from the two .class files of both classes are built together into one object? 还是继承类的.class文件仅包含特定于它的部分,并且在运行时两个类的两个.class文件中的对象详细信息一起构建到一个对象中? If either or both classes was generic, would it have effect on the process? 如果这两个类别中的任何一个或两个都是通用的,对流程有影响吗? Thx. 谢谢。

When A extends B, then only that information is written into the class file for A. 当A扩展B时,则仅将该信息写入A的类文件中。

There is no copying of code of any form from B.class to A.class. 没有从B.class到A.class的任何形式的代码复制。 Meaning: when you change B, there is normally no need to recompile A. 含义:更改B时,通常不需要重新编译A。

And generics are mainly a compile time feature - any generic type turns into Object in bytecode (that is called type erasure ). 泛型主要是编译时的功能-任何泛型类型都将以字节码形式转换为Object (称为类型Erase )。 The class file contains a bit of meta information about which entities were declared as generic type, but thats all. 类文件包含一些有关哪些实体被声明为通用类型的元信息,仅此而已。 In other words: Java generics are not the same thing as C++ templates. 换句话说:Java泛型是一样的东西C ++模板。

The second one, for example if you compile the following two classes: 第二个,例如,如果您编译以下两个类:

public class Parent {
  public void myMethod(String arg) {
  }
}

public class Child extends Parent {
  public void myMethod(String arg) {
    super.myMethod(arg);
  }
}

Then, after you had compiled both classes, you change the Parent class like: 然后,在编译完两个类之后,可以像下面这样更改Parent类:

public class Parent {
  public void myMethod(Integer arg) {
  }
}

You'll get a NoSuchMethodError , this happens because Child call the parent's myMethod at runtime. 您会收到NoSuchMethodError ,这是因为Child在运行时调用了父级的myMethod

I hope it was clear, bye. 我希望清楚,再见。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM