Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get actual type in Java?

Hi I’m new to Java so this question might be ridiculous though, I wonder how to get actual type in Java.

I mean, let’s say there’s a code block as belows:

List<String> foo_list = new ArrayList<>();
ArrayList<String> foo_arrayList = new ArrayList<>();

then foo_list.getClass() and foo_arrayList.getClass() both would return "java.util.ArrayList" right?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

but if I try to pass foo_list into a function that expects ArrayList<String> as a argument, it causes compile time error like follows:

java: method X in class Y cannot be applied to given types;
  required: java.util.ArrayList<java.lang.String>
  found: java.util.List<java.lang.String>
  reason: actual argument java.util.List<java.lang.String> cannot be converted to java.util.ArrayList<java.lang.String> by method invocation conversion

so even though that foo_list.getClass() returns "java.util.ArrayList", I guess(from the error log) its actual type is "java.util.List<java.lang.String>".. (I might guess wrong)

how can I get the "java.util.List<java.lang.String>" with foo_list?

thanks.

>Solution :

You seem to be confusing compile-time type with runtime type. At compile time, your foo_list is indeed a List<String> because that’s how you declared it. The only way to check its compile-time type is to look at your code. Check the place where you declare the variable, and you’ll see what its type is.

At runtime, your foo_list is an ArrayList. (Not an ArrayList<String> because the parameter <String> is lost due to type erasure. By the way, type erasure happens only at runtime. There is no type erasure at compile time.)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading