Why does the outer class appear twice in the gener

2019-07-05 16:11发布

This question already has an answer here:

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条回答
老娘就宠你
2楼-- · 2019-07-05 16:13

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()); //<------------
        }
查看更多
登录 后发表回答