编程语言
首页 > 编程语言> > java-为什么外部类在通用类型名称中出现两次?

java-为什么外部类在通用类型名称中出现两次?

作者:互联网

这个问题已经在这里有了答案:            >            How can I determine the type of a generic field in Java?                                    6个
问:为什么包含类的名称出现两次?

上下文:我正在生成代码,目标是获取源代码中编写的字段声明(完全限定是可以的,但是我需要类型参数):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());
  }
}

输出:

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

更新:
谢谢大家的投入.由于此问题被标记为重复,因此我发布了当前的工作解决方案over there.

解决方法:

genericType是ParameterizedTypeImpl的实例

toString()方法返回ownerType类的名称,然后返回rawType类名.

反编译的代码

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()); //<------------
        }

标签:reflection,code-generation,java
来源: https://codeday.me/bug/20191111/2017979.html