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?

3
  • 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. Commented Mar 22, 2016 at 15:44
  • Here is the code: http://pastebin.com/yeHkcMxq Commented Mar 22, 2016 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. Commented Mar 22, 2016 at 16:47

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.