You actually CAN access generic type at runtime #generics #cor | Java Tech News
You actually CAN access generic type at runtime #generics #corelibs #runtime Generics are used to provide compilation checks for type-safety. They are faded, however, after the compilation and transformed to type casts: List list = new ArrayList(); list.add("Hi"); String x = list.get(0); is compiled into List list = new ArrayList(); list.add("Hi"); String x = (String) list.get(0);
So, how do you identify a type of the compiled List? Turns out you can — by using reflection. Metadata of erased super type is accessible in runtime: this.entityBeanType = ((Class) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0]);
This trick is only possible if your generic class has a superclass, which is a parametrized type. https://xebia.com/blog/acessing-generic-types-at-runtime-in-java/
The channel is dedicated to Java developers who are passionate about learning how the whole Java Platform works. Every post in this channel is a digest of a quality article or reference doc. No bewitc...