用JDI调试Java应用程序

1. 为被调试的程序设置启动参数:
-Xrunjdwp:transport=dt_socket,address=8888,server=y,suspend=n
作为server,打开8888监听,不挂起。

2.把tools.jar加到CLASSPATH里。note: 这个jar包含在JDK中,不在JRE中。

3. 用JDI获取每个类有多少实例:
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import com.sun.jdi.Bootstrap;
import com.sun.jdi.ObjectReference;
import com.sun.jdi.ReferenceType;
import com.sun.jdi.ThreadReference;
import com.sun.jdi.VirtualMachine;
import com.sun.jdi.connect.AttachingConnector;
import com.sun.jdi.connect.Connector;


/**
* @author fanrey
*
*/
public class JDITest {

/**
* @param args
*/
public static void main(String[] args) {
String className = null;
if(args != null && args.length == 1){
className = args[0];
}else
className = "no.axxessit.il.axxrpc.AxxRpcPinger";
List connectors = Bootstrap.virtualMachineManager().allConnectors();
Connector conn = null;
VirtualMachine vm = null;
Iterator iter = connectors.iterator();
while (iter.hasNext()) {
Connector connector = (Connector)iter.next();
if (connector.name().equals("com.sun.jdi.SocketAttach")) {
conn =  connector;
}
}
Map arguments=conn.defaultArguments();
for (Iterator itr=arguments.keySet().iterator(); itr.hasNext();)
{
Connector.Argument argument=(Connector.Argument)
arguments.get(itr.next());
}
Connector.Argument host=(Connector.Argument) arguments.get("hostname");
Connector.Argument port=(Connector.Argument) arguments.get("port");
host.setValue("localhost");
port.setValue("8888");

AttachingConnector attacher=(AttachingConnector) conn;
try {
vm=attacher.attach(arguments);
}
catch (Exception e) {
e.printStackTrace();
}
List<ReferenceType> classList = vm.classesByName(className);
//        System.out.println(classList.size());
//        List<ReferenceType> classList = vm.allClasses();
for(ReferenceType type : classList){
List<ObjectReference> ors = type.instances(0);
System.out.println(type + " instance number: " + ors.size());
}
List<ThreadReference> ts = vm.allThreads();
System.out.println("Thread number: "+ts.size());
}

}

运行结果:
class no.axxessit.il.axxrpc.AxxRpcPinger (loaded by instance of sun.misc.Launcher$AppClassLoader(id=3)) instance number: 1
Thread number: 63

你可能感兴趣的:(java)