简体   繁体   English

使用Java调试接口手动加载类

[英]Manually load classes using Java Debug Interface

Background 背景

I am creating a tool that will turn Java code into a UML Class Diagram. 我正在创建一个将Java代码转换为UML类图的工具。 As I only have 3 weeks to do it, my teacher suggested I use the Java Debug Interface rather than creating a parser to do this task. 由于我只有3周的时间来做,我的老师建议我使用Java调试接口,而不是创建解析器来完成此任务。

Problem 问题

I have registered for the ClassPrepareEvents which shows when a class is loaded by the VM (see code snippet below), however classes are only loaded as and when they are needed. 我已经注册了ClassPrepareEvents,该事件显示了VM何时加载类(请参见下面的代码段),但是仅在需要时加载类。 For example, if clicking on a button in the GUI creates an object of type A, then A won't be loaded until a user clicks on the button. 例如,如果在GUI中单击按钮创建了一个类型为A的对象,则在用户单击该按钮之前,不会加载A。

This needs to be an automated tool, so needs to load all classes within the program without user interaction, so how would one go about manually loading all these classes? 这需要是一种自动化工具,因此需要在没有用户交互的情况下加载程序中的所有类,那么如何手动加载所有这些类呢? Or is there something in the API that I've missed and there's another way of doing this? 还是我错过了API中的某些东西,还有另一种方法呢?

Thanks in advance! 提前致谢! :) :)

Code Snippet 代码段

EventRequestManager em=vm.eventRequestManager();
ClassPrepareRequest cpR = em.createClassPrepareRequest();
cpR.addClassFilter("project.*");
cpR.enable();

EventQueue eventQ=vm.eventQueue();
while (true) {
    EventSet eventSet=null;
    try {
        eventSet=eventQ.remove();
    } catch (Exception e) { // handle the error 
          continue;
    }

    EventIterator eventIterator=eventSet.eventIterator();
    while (eventIterator.hasNext()) {
        Event event=eventIterator.nextEvent();

        if(event instanceof ClassPrepareEvent) {
            ClassPrepareEvent classPrepareEvent = (ClassPrepareEvent)event;
            ReferenceType refType = classPrepareEvent.referenceType();
            System.out.println(refType.name() + " loaded.");
        }
    }
}

I know its 3 months late. 我知道它晚了三个月。

Give a package destination of classes to be loaded. 给出要加载的类的包目的地。 You will need access to the classpath of the javacode you are trying to convert. 您将需要访问您尝试转换的javacode的类路径。

See this post to find classes in a package. 请参阅这篇文章以查找包中的类。 Can you find all classes in a package using reflection? 您可以使用反射找到包中的所有类吗?

Then its just a matter of loading the classes into classloader with Class.forName 然后,只需使用Class.forName将类加载到类加载器中即可

If you still need the class prepare event. 如果您仍然需要上课准备事件。 That should get triggered too. 那也应该被触发。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM