我关注了这篇博客文章。以下是我如何使它工作,以获得对象的大小。
/清单。中频
Manifest-Version: 1.0
Premain-Class: ar.com.docdigital.InstrumentationApp
Can-Redefine-Classes: true
Can-Retransform-Classes: true
Can-Set-Native-Method-Prefix: true
在你的 pom.xml (注意,我们引用自定义清单)
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<configuration>
<archive>
<manifestFile>
MANIFEST.MF
</manifestFile>
<manifest>
<addClasspath>true</addClasspath>
<mainClass>
ar.com.docdigital.App
</mainClass>
</manifest>
</archive>
</configuration>
</plugin>
我的检测代理:
package ar.com.docdigital;
import java.lang.instrument.Instrumentation;
/**
*
* @author juan.fernandez
*/
public class InstrumentationApp {
private static Instrumentation instrumentation;
public static void premain(String args, Instrumentation inst) {
instrumentation = inst;
}
public static long getObjectSize(Object o) {
return instrumentation.getObjectSize(o);
}
}
我的主应用程序:
package ar.com.docdigital;
import static ar.com.docdigital.InstrumentationApp.getObjectSize;
/**
*
* @author juan.fernandez
*/
public class App {
public static void main (String[] args) {
System.out.println("Size of CoprimeLong: " + getObjectSize(new CoprimesList.CoprimeLong(1L)));
System.out.println("Size of Long: " + getObjectSize(new Long(1L)));
}
}
将所有和 CLI 输出放在一起:
$ mvn package
$ java -javaagent:target/primos-0.1.0-SNAPSHOT.jar -jar target/primos-0.1.0-SNAPSHOT.jar
Size of CoprimeLong: 24
Size of Long: 24