简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM