Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getGenericSuperclass() in Java. How does it work?

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");
        }
    }
}
  1. 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:

  2. Is it ok to do it?

like image 625
Gilgamesz Avatar asked Sep 25 '26 03:09

Gilgamesz


1 Answers

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.

like image 114
apangin Avatar answered Sep 27 '26 16:09

apangin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!