如何获取列表的通用类型

时间:2019-05-08 19:45:39

标签: java bcel

我正在使用BCEL库来分析一些代码。我遇到了一种方法(getAllNames()),其返回类型为List< Name >。我希望能够获得此方法的返回类型。

我希望能够获得“名称”的完整类别。

我尝试在方法访问者类中使用< Instruction.getReturnType() >方法,但是对于此特定方法,我得到的结果为“ j​​ava.util.List”。我要使用通用类型“ com.instant.Name”。

方法的签名如下:

public List<Name> getAllNames() {
...
}

在使用org.apache.bcel.classfile.Method访问方法之前,我还创建了一个org.apache.bcel.generic.MethodGen对象。

当我尝试获取返回类型时,它再次给出“ java.util.List”

我希望MethodGen.getReturnType()的输出为“ com.instant.Name”,但实际输出为“ java.util.List”

1 个答案:

答案 0 :(得分:0)

与某些评论相反,信息显然存在,在接口级别上不会发生类型擦除-就像Eclipse / NetBeans / IntelliJ / etc一样。可以获取类成员的确切类型/返回类型,您也可以这样做:

public class Name {
  public List<Name> getAllNames(){return null;}

  public static void main(String[] args) throws Exception {
    Method m=Name.class.getMethod("getAllNames");
    ParameterizedType pt=(ParameterizedType)m.getGenericReturnType();
    System.out.println(pt.getActualTypeArguments()[0]);
  }
}

BCEL是另一个故事,我并不熟悉,但是FieldOrMethod.java的末尾有一种叫做getGenericSignature()的方法。您可能已经发现它很有用(尽管它可能会产生签名),或者您可以在attributes上复制循环(可以通过getAttributes()来获得它们),检查是否{ 1}}:

instanceof Signature

真正的代码表明只能有一个这样的属性,然后循环可能随后退出,但这使我想到了具有多个参数的类型,例如Attribute a[]=m.getAttributes(); // where is the org.apache.bcel.classfile.Method you have for(int i=0;i<a.length;i++) if(a[i] instanceof Signature) System.out.println(a[i]); // this is just a test of course. -s ...
Map本身在其他任何地方都没有发生(未经测试,也没有使用),所以我只能希望它(因此,上述方法)确实有效。

相关问题