为什么外部类在通用类型名称中出现两次? [英] Why does the outer class appear twice in the generic type name?

查看:64
本文介绍了为什么外部类在通用类型名称中出现两次?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问:为什么包含类的名称出现两次?

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

上下文:我正在生成代码,目标是获取字段的声明,如源代码中所写(完全合格可以,但是我需要类型参数): test.Foo.Bar< java.lang.String>

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

输出:

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

更新:
谢谢大家您的输入。由于此问题被标记为重复,因此我在那里发布了我当前的工作解决方案

推荐答案

genericType是ParameterizedTypeImpl的实例

genericType is instance of ParameterizedTypeImpl

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

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

反编译的代码段

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

这篇关于为什么外部类在通用类型名称中出现两次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆