Let's consider the following piece of code:
package index;
public class Main {
public static void main(String[] args) {
Inner inner = new Inner();
Type t = inner.getClass().getGenericSuperclass();
ParameterizedType p = (ParameterizedType) t;
Type[] a = p.getActualTypeArguments();
try {
Custom c = (Custom) ((Class) a[0]).newInstance();
c.f();
} catch (Exception e){}
}
private static abstract class AbstractClass<T> {
public abstract void doSth();
}
private static class Inner extends AbstractClass<Custom>{
public void doSth() {
}
}
private static class Custom{
public Custom(){
}
public void f(){
System.out.println("Custom");
}
}
}
It works and I cannot understand how does it works. It shows that it is possible to get information about superclasses parameters. I don't know how it is possible to get a such information because I looked at bytecode and there is no such information:
Is it ok to do it?
There is a Signature attribute in .class file, see JVMS §4.7.9.
If you decompile Main.Inner with javap -verbose, you'll find this attribute:
Signature: #14 // Lindex/Main$AbstractClass<Lindex/Main$Custom;>;
Class.getGenericSuperclass implementation extracts this attribute with the help of a native method and then parses, validates and converts it to Java representation. So, it is absolutely possible and OK to get this information.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With