Why does the outer class appear twice in the generic type name? [duplicate]

≯℡__Kan透↙ 提交于 2020-01-04 04:46:27

问题


Q: Why does the name of the containing class appear twice?

Context: I'm generating code and the goal is to get the declaration of the field, as written in the source (fully qualified is fine, but I need the type parameter): test.Foo.Bar<java.lang.String>

package test;

import java.lang.reflect.Field;
import java.lang.reflect.Type;

public class Foo
{
  public static class Bar<TYPE> {}

  private Bar<String> bar;

  public static void main(String[] args) throws Exception
  {
    Field field = Foo.class.getDeclaredField("bar");
    Type genericType = field.getGenericType();
    Type type = field.getType();

    System.out.println("genericType: " + genericType.getTypeName());
    System.out.println("       type: " + type.getTypeName());
  }
}

Output:

genericType: test.Foo.test.Foo$Bar<java.lang.String>
       type: test.Foo$Bar

UPDATE: Thank you everyone for your input. Since this question was marked as duplicate, I posted my current working solution over there.


回答1:


genericType is instance of ParameterizedTypeImpl

the toString() method returns ownerType class' name and then rawType classname.

The decompiled piece of the code

public String toString() {
    StringBuilder var1 = new StringBuilder();
    if(this.ownerType != null) {
        if(this.ownerType instanceof Class) {
            var1.append(((Class)this.ownerType).getName()); //<---
        } else {
            var1.append(this.ownerType.toString());
        }

        var1.append(".");
        if(this.ownerType instanceof ParameterizedTypeImpl) {
            var1.append(this.rawType.getName().replace(((ParameterizedTypeImpl)this.ownerType).rawType.getName() + "$", ""));
        } else {
            var1.append(this.rawType.getName()); //<------------
        }


来源:https://stackoverflow.com/questions/45083186/why-does-the-outer-class-appear-twice-in-the-generic-type-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!