Introduction
Today at lunch we had a chat about generics and their implementation in Java. Generics are available since Java 5. To stay byte code compatible between Java 1.4 and 5 generics are implemented by using type erasure. That means that at compile time all generic types are striped out and the resulting byte code only contains raw types like:
List a = ArrayList();
instead of
List<MyType> a = new ArrayList<MyType>();
This means that when we read elements of the list at runtime there needs be a cast added to check that both sides of the assignment have a compatible type:MyType a = (MyType)list.get(0);
instead of
MyType a = list.get(0);
Java Class File Disassembler
To analyse how this cast is actually implemented in Java byte code one can use the Java Class File Disassembler. This command line tool ships with every Oracle JDK distribution and is called
javap.
To inspect the byte code of a given class file use the command:
javap -c <classfile>
For example:
javap -c org.henrikeichenhardt.javabytecode.Main
The output can get quite verbose and it makes sense to boil down the problem you want to look at to a few lines of code - just enough so you can create and compile you scenario.
Under the hood
For our scenario the Java code would look like this:
package org.henrikeichenhardt.javabytecode;
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(final String[] args) {
final List<Main> list = new ArrayList<Main>();
list.add(new Main());
final Main value = list.get(0);
}
}
We simply create an java.util.ArrayList
with type of Main
and add one element to this list. Then we retrieve this element again from the list. This few lines of code result in the following output of javap
:
Compiled from "Main.java"
public class org.henrikeichenhardt.javabytecode.Main extends java.lang.Object{
public org.henrikeichenhardt.javabytecode.Main();
Signature: ()V
Code:
0: aload_0
1: invokespecial #8; //Method java/lang/Object."<init>":()V
4: return
public static void main(java.lang.String[]);
Signature: ([Ljava/lang/String;)V
Code:
0: new #16; //class java/util/ArrayList
3: dup
4: invokespecial #18; //Method java/util/ArrayList."<init>":()V
7: astore_1
8: aload_1
9: new #1; //class org/henrikeichenhardt/javabytecode/Main
12: dup
13: invokespecial #19; //Method "<init>":()V
16: invokeinterface #20, 2; //InterfaceMethod java/util/List.add:(Ljava/lang/Object;)Z
21: pop
22: aload_1
23: iconst_0
24: invokeinterface #26, 2; //InterfaceMethod java/util/List.get:(I)Ljava/lang/Object;
29: checkcast #1; //class org/henrikeichenhardt/javabytecode/Main
32: astore_2
33: return
}
The first block of information beginning with
public org.henrikeichenhardt.javabytecode.Main();
is the code to generate the (implicit) constructor of the Main
object. We can ignore this for now. The second block of information is the byte code representing the code of the static main method public static void main(java.lang.String[]);
On the first few lines the instances of the ArrayList is created and a reference is stored in on the stack. Then an instance of the Main
object is created and added to the list. Now lets focus on reading an element from the list:final Main value = list.get(0);
This resulting Java byte code looks like this:
24: invokeinterface #26, 2; //InterfaceMethod java/util/List.get:(I)Ljava/lang/Object;
29: checkcast #1; //class org/henrikeichenhardt/javabytecode/Main
32: astore_2
Without going into to much detail here what basically happens is that invokeinterface
calls the method get
of our list and puts the result on top of the stack. Then the command checkcast
is executed. It takes only one argument which is a reference to the type which needs to be checked (Main). This type is then compared with the top of the stack (where we previously put the result of list.get(0)
).
How does checkcast work?
The documentation of the
checkcast
instruction reveals how this check is done:- If the stack reference is
null
nothing happens. - If the stack reference can be cast to the type provided nothing happens.
- Otherwise a
ClassCastException
is thrown.
That means that
So what the problem boils down to is how does
It is now up to the JVM implementation how efficient this checks are executed and if any profiling or heuristics are applied. In our example S is an ordinary class and T is a class type and both are the same which satisfies the first case above.checkcast
is very similar to an instanceOf
test. If the checkcast
test is passed execution continues normally and the top of the stack is stored in a local variable.So what the problem boils down to is how does
checkcast
know if it can cast a value to a type? The following is copied from [1]:The following rules are used to determine whether an objectref that is notnull
can be cast to the resolved type: if S is the class of the object referred to by objectref and T is the resolved class, array, or interface type, checkcast determines whether objectref can be cast to type T as follows:
If S is an ordinary (nonarray) class, then:
If T is a class type, then S must be the same class as T, or S must be a subclass of T; If T is an interface type, then S must implement interface T. If S is an interface type, then:
If T is a class type, then T must beObject
. If T is an interface type, then T must be the same interface as S or a superinterface of S. If S is a class representing the array type SC[]
, that is, an array of components of type SC, then:
If T is a class type, then T must beObject
. If T is an interface type, then T must be one of the interfaces implemented by arrays (JLS §4.10.3). If T is an array type TC[]
, that is, an array of components of type TC, then one of the following must be true:
TC and SC are the same primitive type. TC and SC are reference types, and type SC can be cast to TC by recursive application of these rules.
[1] Oracle checkcast
Please share more like that. GENERICS
ReplyDeleteHenrik Eichenhardt'S Blog: How Are Java Generics Implemented Under The Hood? >>>>> Download Now
Delete>>>>> Download Full
Henrik Eichenhardt'S Blog: How Are Java Generics Implemented Under The Hood? >>>>> Download LINK
>>>>> Download Now
Henrik Eichenhardt'S Blog: How Are Java Generics Implemented Under The Hood? >>>>> Download Full
>>>>> Download LINK FG
Given so much info in it, These type of articles keeps the users interest in the website, and keep on sharing more .
ReplyDeletejava training in chennai | Best java training in chennai | java training | java training in chennai with placement
The knowledge of technology you have been sharing thorough this post is very much helpful to develop new idea. here by i also want to share this.
ReplyDeletefull stack developer training in annanagar
full stack developer training in tambaram
full stack developer training in velachery
Awesome article. It is so detailed and well formatted that i enjoyed reading it as well as get some new information too.
ReplyDeletepython training in rajajinagar
Python training in btm
Python training in marathahalli
Good Post, I am a big believer in posting comments on sites to let the blog writers know that they ve added something advantageous to the world wide web.
ReplyDeleteData Science training in rajaji nagar
Data Science training in chennai
Data Science training in electronic city
Data Science training in USA
Data science training in pune
Data science training in kalyan nagar
Really you have done great job,There are may person searching about that now they will find enough resources by your post
ReplyDeleteangularjs Training in chennai
angularjs-Training in pune
angularjs-Training in chennai
angularjs Training in chennai
angularjs-Training in tambaram
I appreciate your efforts because it conveys the message of what you are trying to say. It's a great skill to make even the person who doesn't know about the subject could able to understand the subject . Your blogs are understandable and also elaborately described. I hope to read more and more interesting articles from your blog. All the best.
ReplyDeleteMicrosoft Azure online training
Selenium online training
Java online training
Java Script online training
Share Point online training
It is very good and very informative. There is a useful information in it.Thanks for posting...
ReplyDeletehttps://www.apponix.com/Java-Institute/Java-Training-Institute-in-Bangalore.html
This comment has been removed by the author.
ReplyDeleteNice Article
ReplyDeleteDevOps Training in Chennai
Hadoop Big Data Training
Hi,
ReplyDeleteGood job & thank you very much for the new information, i learned something new. Very well written. It was sooo good to read and usefull to improve knowledge. Who want to learn this information most helpful. One who wanted to learn this technology IT employees will always suggest you take python training in pune. Because python course in pune is one of the best that one can do while choosing the course.
Thanks for your informative article.
ReplyDelete"Pressure Vessel Design Course is one of the courses offered by Sanjary Academy in Hyderabad. We have offer professional
Engineering Course like Piping Design Course,QA / QC Course,document Controller course,pressure Vessel Design Course,
Welding Inspector Course, Quality Management Course, #Safety officer course."
Piping Design Course in India
Piping Design Course in Hyderabad
Piping Design Course in Hyderabad
QA / QC Course
QA / QC Course in india
QA / QC Course in Hyderabad
Document Controller course
Pressure Vessel Design Course
Welding Inspector Course
Quality Management Course
Quality Management Course in india
Safety officer course
For ethical hackers ceh certification is very helpful
ReplyDeleteOracle offers varoious technolgoies pl sql, sql etc. oracle pl sql training is mainly for pl sql training
ReplyDeleteGood, keep posting
ReplyDeleteinterview-questions/aptitude/permutation-and-combination/how-many-groups-of-6-persons-can-be-formed
tutorials/oracle/oracle-delete
technology/chrome-flags-complete-guide-enhance-browsing-experience/
interview-questions/aptitude/time-and-work/a-alone-can-do-1-4-of-the-work-in-2-days
interview-questions/programming/recursion-and-iteration/integer-a-40-b-35-c-20-d-10-comment-about-the-output-of-the-following-two-statements
1croreprojects offers the best 2019 robotics projects chennai for final year students.
ReplyDeleteVisit :-
https://meprojectschennai.co.in
Phone : +91 97518 00789 / +91 77081 50152
nice.............
ReplyDeleteinplant training in chennai
inplant training in chennai
inplant training in chennai for it.php
algeeria hosting
angola hostig
shared hosting
bangladesh hosting
botswana hosting
central african republi hosting
shared hosting
nice..
ReplyDeletehosting
india hosting
india web hosting
iran web hosting
technology 11 great image sites like imgur hosting
final year project dotnet server hacking what is web hosting
macao web hosting
inplant training in chennai
inplant training in chennai
inplant training in chennai for it.php
good
ReplyDeleteinplant training in chennai
inplant training in chennai
inplant training in chennai for it.php
italy web hosting
afghanistan hosting
angola hosting
afghanistan web hosting
bahrain web hosting
belize web hosting
india shared web hosting
I must appreciate you for providing such a valuable content for us. This is one amazing piece of article. Helped a lot in increasing my knowledge.
ReplyDeleteoracle training in bangalore
This is really an amazing article. Your article is really good and your article has always good thank you for information.
ReplyDeletehadoop training in bangalore
hadoop courses in bangalore
hadoop classes in bangalore
hadoop training institute in bangalore
hadoop course syllabus
best hadoop training
hadoop training centers
Many websites have differenet information but in your blog you shared unique and useful information. Thanks
ReplyDeletetableau training in bangalore
tableau courses in bangalore
tableau classes in bangalore
tableau training institute in bangalore
tableau course syllabus
best tableau training
tableau training centers
I like your such a valuable post for us. It is one of the excellent articles for this topic. It is very helpful for me and keeps doing...
ReplyDeleteTableau Training in Chennai
Tableau Course in Chennai
Power BI Training in Chennai
Graphic Design Courses in Chennai
Oracle DBA Training in Chennai
Pega Training in Chennai
Linux Training in Chennai
Placement Training in Chennai
Soft Skills Training in Chennai
Appium Training in Chennai
Tableau Training in Velachery
Tableau Training in OMR
thank you sharing this blog, this information is useful for understanding the java for beginner.
ReplyDeletejava training bangalore
javascript training bangalore
I’ve desired to post about something similar to this on one of my blogs and this has given me an idea. Cool Mat.lovely page.
ReplyDeleteAi & Artificial Intelligence Course in Chennai
PHP Training in Chennai
Ethical Hacking Course in Chennai Blue Prism Training in Chennai
UiPath Training in Chennai
Damien Grant
ReplyDeleteDamien Grant
Damien Grant
Damien Grant
Damien Grant
Damien Grant
Damien Grant
Damien Grant
This information is impressive. I am inspired with your post. Thank you so much for your information its very useful and helpful to me keep updating and sharing.
ReplyDeleteData science training
Data Analytics Training
Devops training
Selenium training
AWS Training courses and certification
ReplyDeleteNice blog! Thanks for sharing this valuable information
DevOps Training in Bangalore
Devops Training in Pune
Devops Training in Hyderabad
devops training in gurgaon
Grab the <a href="https://infycletechnologies.com/digital-marketing-course-in-chennai/</a>Digital Marketing Training in Chennai</a. from Infycle Technologies, the best software training institute, and Placement center in Chennai which is providing professional software courses such as Data Science, Artificial Intelligence, Cyber Security, Big Data, Java, Hadoop, Selenium, Android, and iOS Development, DevOps, Oracle, etc with 100% hands-on practical training. Dial 7502633633 to get more info and a free demo and to grab the certification for having a peak rise in your career.
ReplyDeleteWonderful post and more informative!keep sharing Like this!
ReplyDeleteFuture of SEO
What is the Future of SEO
Thanks you for sharing this unique useful information content with us. Really awesome work. keep on blogging.
ReplyDeleteinternship for web development | internship in electrical engineering | mini project topics for it 3rd year | online internship with certificate | final year project for cse
This post is so interactive and informative.keep update more information...
ReplyDeletehadoop training in tambaram
Big data training in chennai
Mindblowing blog very useful thanks
ReplyDeleteAWS Training in Velachery
AWS Training in Chennai
This comment has been removed by the author.
ReplyDeleteThis comment has been removed by the author.
ReplyDeleteThis comment has been removed by the author.
ReplyDeleteExcellent article with lots of information and thanks for sharing
ReplyDeletePython Training in Kolkata
Python Training in Hyderabad
Henrik Eichenhardt'S Blog: How Are Java Generics Implemented Under The Hood? >>>>> Download Now
ReplyDelete>>>>> Download Full
Henrik Eichenhardt'S Blog: How Are Java Generics Implemented Under The Hood? >>>>> Download LINK
>>>>> Download Now
Henrik Eichenhardt'S Blog: How Are Java Generics Implemented Under The Hood? >>>>> Download Full
>>>>> Download LINK Nf
Great post. keep sharing such a worthy information.
ReplyDeleteGraphic Design courses in Chennai
Online Graphic Design Course
Graphic Design Courses In Bangalore
Your weblog supplied us later than acid records to perform-court combat bearing in thoughts. each & all recommendations of your display are first-rate. thanks plenty for sharing. keep blogging, ! Quotes On Brothers Day
ReplyDeleteNice work.Revo Uninstaller Pro Crack
ReplyDelete