简体   繁体   中英

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. 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. But when I start my program without copying file first (I mean when I let it do to my program) I got 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. Any help will be appreciated.

It seems you'll have to get familiar with the JavaCompiler API to do this. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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