简体   繁体   English

获取在运行时创建的类

[英]Get class created at runtime

I'm trying to copy a .java file containing a class (MyTestClass in package "test") from some place on my disk. 我正在尝试从磁盘上的某个位置复制一个包含类(包“ test”中的MyTestClass)的.java文件。 I want to get class which this file contains. 我想获取此文件包含的类。 Maybe my code will be useful. 也许我的代码会有用。 This is my code: 这是我的代码:

File generatedFile = new File( DIR_CONTAINING_FILE + "/" + className + ".java" );
FileUtils.copyFileToDirectory( generatedFile, COPY_FILE_DIR );
Class cl = Class.forName( "test.MyTestClass" );

Copying file works fine. 复制文件工作正常。 It shows where it has to be. 它显示了它必须在哪里。

When I copy my file to COPY_FILE_DIR manually and then start program it will work, it will find my class. 当我手动将文件复制到COPY_FILE_DIR并启动程序后,它将起作用,它将找到我的班级。 But when I start my program without copying file first (I mean when I let it do to my program) I got ClassNotFoundException. 但是,当我不首先复制文件而启动程序时(我的意思是当我将其放到程序中时),我得到了ClassNotFoundException。 When I refresh directories there's my file, so it has been copied perfectly. 当我刷新目录时,有我的文件,因此已被完美复制。

In this moment I can start my program again and.. magic! 在这一刻,我可以再次启动我的程序了,..魔术! it will find my class! 它会找到我的课! Looks like I need to refresh directories from java or do something else.. I don't know what to do. 看来我需要从Java刷新目录或执行其他操作。我不知道该怎么办。 Any help will be appreciated. 任何帮助将不胜感激。

It seems you'll have to get familiar with the JavaCompiler API to do this. 看来您必须熟悉JavaCompiler API才能执行此操作。 It's not really important where you store your .java Files - they have to be compiled to bytecode before you can try to use them inside the runtime. 存储.java文件的位置并不是很重要-必须先将它们编译为字节码,然后才能尝试在运行时内部使用它们。

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

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