1

I am working on a project that creates Java classes from xsd. At run-time, I want to create classes and read names of these classes. However, when I first run the project (before classes are created) it gives me an error that says "java.lang.ClassNotFoundException: generated.classes.AddressType" . If I run again , without changing anything (classes are created at this point) , it does not give me an error. I used "com.sun.tools.xjc.api" for creating classes. When I want to read class names, I simply do that

File folder = new File(System.getProperty("user.dir")+"\\src\\generated\\classes");
    File[] listOfFiles = null;
    List<String> namesOfClasses = new ArrayList<>();
    listOfFiles=folder.listFiles();
    for(File file: listOfFiles){
            try {
                    if(!file.getName().equals("ObjectFactory.java")){
                        String classname="generated.classes."+file.getName().substring(0, file.getName().length() - 5);
                        namesOfClasses.add(classname);
                    }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    return namesOfClasses;

It seems , new created classes cannot be seen at runtime. How can I make this classes read at runtime?

Enver Evci
  • 186
  • 6
  • I don't see how the shared code can throw `ClassNotFoundException`. As reading class names from the directory has nothing to do with class loading. – Tirath Mar 22 '16 at 15:44
  • Here is the code: [http://pastebin.com/yeHkcMxq](http://pastebin.com/yeHkcMxq) – Enver Evci Mar 22 '16 at 15:51
  • My guess - your code generates `.java` files and we need `.class` to load a class. I'm guessing you are using an IDE have the automatic build on or something that's how your program is picking the `class` files in the next run. – Tirath Mar 22 '16 at 16:47

1 Answers1

0

You may compile your classes on the fly like (by answer):

    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    compiler.run(null, null, null, files);

Please look at similar questions for other alternatives:

And I do exactly that in test of my xjc-documentation-annotation-plugin : XJCPluginDescriptionAnnotationTest it may be used as step-by-step tutorial.

Hubbitus
  • 5,161
  • 3
  • 41
  • 47