试试这个,对你有帮助,
Allocation Instrumenter 是使用 java.lang.instrument API 和 ASM 编写的 Java 代理。 Java 程序中的每个分配都经过检测;每次分配都会调用用户定义的回调。
为了编写自己的分配跟踪代码,您必须实现 Sampler 接口并将其实例传递给 AllocationRecorder.addSampler():
AllocationRecorder.addSampler(new Sampler() {
public void sampleAllocation(int count, String desc,
Object newObj, long size) {
System.out.println("I just allocated the object " + newObj +
" of type " + desc + " whose size is " + size);
if (count != -1) { System.out.println("It's an array of size " + count); }
}
});
您还可以使用分配检测器来检测特定类的构造函数。为此,您可以实例化一个 ConstructorCallback 并将其传递给 ConstructorInstrumenter.instrumentClass()
try {
ConstructorInstrumenter.instrumentClass(
Thread.class, new ConstructorCallback<Thread>() {
@Override public void sample(Thread t) {
System.out.println("Instantiating a thread");
}
});
} catch (UnmodifiableClassException e) {
System.out.println("Class cannot be modified");
}
项目源代码可在此处获得
https://code.google.com/p/java-allocation-instrumenter/
通过上面给出的解决方案在 android 中,这也可以使用具有分配跟踪器的 ddms 工具
安卓系统自带的。您可以开始跟踪所有对象的分配以及它们分配位置的堆栈跟踪。但是,此工具可以生成大量信息,而您想要的特定信息并不总是易于解析或查找。如果你有 Sun JVM 的版本,我会推荐使用 Kai 提到的工具,它们更发达。如果您必须在 Android 中执行此操作,使用分配跟踪器将为您提供一个开始。