【问题标题】:Using JAXB to load a .java file into clasloader使用 JAXB 将 .java 文件加载到 clasloader
【发布时间】:2016-06-15 15:33:30
【问题描述】:

我正在编写一个从 JAXB 创建和生成 JavaFileObjects 的程序。目前我已经做到了,所以我的 .java 文件是使用 JAXB 制作的,然后加载到一个数组中。我想获取 JavaFileObjects 并将它们传递给 JAXB 并让 JAXB 编译和类加载它们以用于进一步处理。

当前生成 .java 文件的代码是:

    String outputDirectory = jaxbPackageGenFolderCreation();

            // Setup schema compiler
            SchemaCompiler sc = XJC.createSchemaCompiler();
            sc.forcePackageName(getPackageName());
            LOG.info("PackageName: " + getPackageName());
            LOG.info("creating BINDINGS_XJB: " + MageekConstants.BINDINGS_XJB);
            File bindings = new File(MageekConstants.BINDINGS_XJB);

            /*
            * sc.getOptions.addBindFile adds the xjc bindings file to the the schema compiler. 
            * This method shows deprecated, however it is not being removed from future 
            * versions of the API. It is not being maintained in future versions so the 
            * developers have it annotated as depreciated as a notification tool. Future 
            * stability of this call is NOT guaranteed.
            */
            sc.getOptions().addBindFile(bindings);
            // Setup SAX InputSource
            LOG.info("schema file: " + getXsdFile());
            File schemaFile = new File(getXsdFile());
            InputSource is = new InputSource(schemaFile.toURI().toString());

            // Parse & build
            sc.parseSchema(is);
            S2JJAXBModel model = sc.bind();
            JCodeModel jCodeModel = model.generateCode(null, null);

            String[] splitArray = null;
            try
            {
                PrintStream printStream = new PrintStream(new File(MageekConstants.TEMP_DIR
                        + "GeneratedFiles.mageek"));
                jCodeModel.build(new File(outputDirectory), printStream);

//              ByteArrayOutputStream baos = new ByteArrayOutputStream();
//              CodeWriter codeWriter = new SingleStreamCodeWriter(baos);
//              jCodeModel.build(codeWriter);

我已经研究了内存中的 java 编译和其他方法,但没有任何 IO 到磁盘似乎没有做我想做的事。一位朋友告诉我,JAXB 可以获取 .java 文件,然后对它们进行类加载。我没有找到关于此或示例的文档。任何帮助都会很棒。

【问题讨论】:

    标签: java xml xsd jaxb classloader


    【解决方案1】:

    您可以像 (by answer) 一样即时编译您的类:

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

    请查看类似问题的其他替代方案:

    【讨论】:

      猜你喜欢
      • 2014-05-04
      • 1970-01-01
      • 2013-07-14
      • 2017-03-13
      • 2023-04-01
      • 2023-03-07
      • 1970-01-01
      • 2011-01-14
      相关资源
      最近更新 更多