Java查询依赖是否存在,查找Java类中的所有依赖项

I'm trying to get all dependencies in a Java class, including classes used for generics parametrization and local variables types. So far best framework I've found is apache bcel. Using it I can easily find all fields, method arguments and local variables from byte code. Basically everything except of generics and local variables types. For example, from line List points = new ArrayList(); I can only find one dependency - ArrayList using JavaClass.getConstantPool() method from bcel. It can't detect neither List interface nor Point class. I also tried tattletale and CDA, unfortunately without success (the same results). Examining imports is not enough - I need also dependencies from the same package and I can't accept wildcards. I would be grateful for any help.

解决方案

I've finally found solution. ASM Bytecode Framework is the right tool to use. Using official tutorial and right example it's quite easy to get all needed dependencies. In the example there is already a visitor class DependencyVisitor which does what I want. To get right formatting I had to change only one method in DependencyVistitor example code, so it adds full class names instead of packages only:

private String getGroupKey(String name)

{

//Just comment that block so you can get full class names instead of package only

/*

int n = name.lastIndexOf('/');

if (n > -1)

{

name = name.substring(0, n);

}

*/

// Replace resource char with package separator char

packages.add(name.replace("/", "."));

//packages.add(name);

return name;

}

Looking at DependencyVisitor code you can easily understand what it does and modify it to your needs. Running it on my example class it gives me nice, useful output:

[java.util.ArrayList, java.lang.Object, java.util.List, java.awt.Point, goobar.test.asmhello.TestClass, java.lang.String, java.lang.Integer, java.awt.Graphics, goobar.test.asmhello.TestClass2]. It contains every class and interface I've used and every type used for generics parameterization.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值