logo
down
shadow

Compiling generated code and jar with JavaCompiler


Compiling generated code and jar with JavaCompiler

By : Liltaw10
Date : November 22 2020, 02:42 PM
it helps some times I have generated code that can be compiled on commandline with javac compiler like this: , Try to specify classpath option on your java compiler:
code :
List<String> optionList = new ArrayList<String>();
// set compiler's classpath to the path of your framework-core.jar
optionList.addAll(Arrays.asList("classpath","/lib/framework-core.jar"));
...
compiler.getTask(null, fileManager, null, optionList, null, compilationUnits1).call();    


Share : facebook icon twitter icon
compiling and running user code with JavaCompiler and ClassLoader

compiling and running user code with JavaCompiler and ClassLoader


By : Mélanie Couillard
Date : March 29 2020, 07:55 AM
wish helps you
How can i protect my app from endless loop, and evil students ;)
Compiling directories with JavaCompiler

Compiling directories with JavaCompiler


By : hui tong
Date : March 29 2020, 07:55 AM
help you fix your problem Get all the files from the directory (using directory.listFiles()), and pass the resulting array to getJavaFileObject(File...)
JavaCompiler not compiling files properly

JavaCompiler not compiling files properly


By : Avadhoot
Date : March 29 2020, 07:55 AM
help you fix your problem Most likely, this has nothing to do with the compiler. My guess is that this is because of an error in the source file. Did you remember to import the appropriate classes and interfaces?
Your IntegerComparator.java file needs to contain the import:
code :
import java.util.Comparator; // <--- Import!

public class IntegerComparator 
      implements Comparator<Integer>{

   public IntegerComparator(){}

   public int compare(Integer a, Integer b){
      int aValue = a.intValue();
      int bValue = b.intValue();
      return (aValue - bValue);
   }
}
(JavaCompiler) Compiling multiple files at the same time

(JavaCompiler) Compiling multiple files at the same time


By : user3282266
Date : March 29 2020, 07:55 AM
To fix this issue From the comments, I tried instead of files[i].getPath() to pass the compiler a String[] containing all paths for all files. Below is the solution.
code :
import javax.tools.*;
import java.io.*;
import java.util.*;

public class SimpleCompileTest 
{
    public static void main(String[] args) 
    {

        try{
            File[] files;
            File dir = new File("Thing");
            files = dir.listFiles(new FilenameFilter() {
                public boolean accept(File dir, String name) {
                    return name.toLowerCase().endsWith(".java");
                }
            });
            String[] filenames = new String[files.length];
            for(int i = 0; i < files.length; i++)
                filenames[i] = files[i].getName();

        File file = new File("Errors.txt");
        try{
            FileOutputStream errorStream = new FileOutputStream("Errors.txt");

            JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();

                int compilationResult = compiler.run(null, null, errorStream, filenames);
                        if(compilationResult == 0){
                            System.out.println("Compilation is successful");
                        }else{
                            System.out.println("Compilation Failed");
                        }
        }catch(Exception e)
        {
            System.out.println("error in compiler");
        }
    }catch(Exception h)
    {
        System.out.println("error in filename");
    }
    }

}
Java JavaCompiler.run() compiling anonymous classes as well

Java JavaCompiler.run() compiling anonymous classes as well


By : dfghj
Date : March 29 2020, 07:55 AM
Any of those help Apparently, your loadStrategyClass is defined within a custom ClassLoader. The problem is that it is not enough to call defineClass once for the class you’re interested in, your class loader must be able to resolve classes on demand, usually by implementing findClass, so the JVM can resolve dependencies, like the inner classes.
You didn’t specify, how you get the strategyClassFile argument for the loadStrategyClass method. Since you ran the compiler without any options, I suppose you simply looked up the file relative to the source file. To resolve other dependencies, the actual root of the class directory needs to be known. It becomes much easier when you define where to store the class files, e.g.
code :
// customize these, if you want, null triggers default behavior
DiagnosticListener<JavaFileObject> diagnosticListener = null;
Locale locale = null;

JavaCompiler c = ToolProvider.getSystemJavaCompiler();
StandardJavaFileManager fm
    = c.getStandardFileManager(diagnosticListener, locale, Charset.defaultCharset());

// define where to store compiled class files - use a temporary directory
Path binaryDirectory = Files.createTempDirectory("compile-test");
fm.setLocation(StandardLocation.CLASS_OUTPUT,
               Collections.singleton(binaryDirectory.toFile()));

JavaCompiler.CompilationTask task = c.getTask(null, fm,
    diagnosticListener, Collections.emptySet(), Collections.emptySet(),
    // to make this a stand-alone example, I use embedded source code
    Collections.singleton(new SimpleJavaFileObject(
        URI.create("string:///Class1.java"), Kind.SOURCE) {
            public CharSequence getCharContent(boolean ignoreEncodingErrors) {
                return "package test;\npublic class Class1 { public class Inner {} }";
            }
        }));
if(task.call()) try {
    URLClassLoader cl = new URLClassLoader(new URL[]{ binaryDirectory.toUri().toURL() });
    Class<?> loadedClass = cl.loadClass("test.Class1");
    System.out.println("loaded "+loadedClass);
    System.out.println("inner classes: "+Arrays.toString(loadedClass.getClasses()));
} catch(ClassNotFoundException ex) {
    ex.printStackTrace();
}
public static Class<?> compile(
    DiagnosticListener<JavaFileObject> diagnosticListener,
    Locale locale, String sourceFile) throws IOException, ClassNotFoundException {

    JavaCompiler c = ToolProvider.getSystemJavaCompiler();
    StandardJavaFileManager fm
        = c.getStandardFileManager(diagnosticListener, locale, Charset.defaultCharset());

    // define where to store compiled class files - use a temporary directory
    Path binaryDirectory = Files.createTempDirectory("compile-test");
    fm.setLocation(StandardLocation.CLASS_OUTPUT,
                   Collections.singleton(binaryDirectory.toFile()));

    JavaCompiler.CompilationTask task = c.getTask(null, fm,
        diagnosticListener, Collections.emptySet(), Collections.emptySet(),
        fm.getJavaFileObjects(new File(sourceFile)));
    if(task.call()) {
        Class<?> clazz = null;
        URLClassLoader cl = new URLClassLoader(new URL[]{binaryDirectory.toUri().toURL()});
        for(JavaFileObject o: fm.list(
            StandardLocation.CLASS_OUTPUT, "", Collections.singleton(Kind.CLASS), true)) {

            String s = binaryDirectory.toUri().relativize(o.toUri()).toString();
            s = s.substring(0, s.length()-6).replace('/', '.');
            clazz = cl.loadClass(s);
            while(clazz.getDeclaringClass() != null) clazz = clazz.getDeclaringClass();
            if(Modifier.isPublic(clazz.getModifiers())) break;
        }
        if(clazz != null) return clazz;
        throw new ClassNotFoundException(null,
            new NoSuchElementException("no top level class generated"));
    }
    throw new ClassNotFoundException(null,
        new NoSuchElementException("compilation failed"));
}
Related Posts Related Posts :
  • IntelliJ - include pom.xml dependencies in lib directory
  • Tomcat 7 : Filtering lifecycle events
  • JSONException: Names must be strings
  • Build Spark JavaRDD List from DropResult objects
  • Include css file in richlet with zk
  • Jackson CSV's WRAP_AS_ARRAY
  • Priority for a web request in Java web applications
  • Is there a better way to format this timestamp to ISO8601?
  • Issue with Spring Scope
  • How to declare and use an array of dictionaries from Python in Java and filter them?
  • Wrong weekdays from Calendar.getDisplayName()
  • ClassNotFoundException when creating new ClassPathXmlApplicationContext
  • Java Method Call from Thread
  • Remove background noise from image to make text more clear for OCR
  • PostgreSQL query always return true
  • How to connect FX controller with main app
  • Is there a difference between these two code snippets, and if so what?
  • When two interfaces have conflicting return types, why does one method become default?
  • Updating database throws errors in To Do List app
  • Where does the url come from?
  • Dagger 2 issue overriding single provides annotated method from a module in a library which app uses
  • Better way then If(x instanceof y) in Java?
  • how to debug maven enunciate plugin tomcat web service
  • Spring Context Initialization fails when upgrading to version 4.2.3
  • spring boot cannot connect to rabbitmq
  • How to Run Unit Test in Parallel Across All Modules Using Maven?
  • Getting the next Value in a ArrayList(Not working)
  • How to wait for a MouseListener mouse press?
  • Java RMI: Blocking for void method return?
  • Get Table Properties out of Hive using Java API
  • Read CSV file and write to another CSV - ArrayIndexOutOfBoundsException and pattern difficuties
  • Set LineChart(javafx) style to a child element
  • ArrayList how catch exception on one item from constructor
  • java.lang.NumberFormatException: For input string: " 1"
  • Dekker's Algorithm not working fine for three processes
  • Maven javadoc plugin - package does not exist
  • NotOLE2FileException: Invalid header signature; read 0x0000000000000000, expected 0xE11AB1A1E011CFD0
  • NullPointerExcpetion on findViewById
  • Java ArrayList initialization
  • Problems on making a Tic Tac Toe Game in Java
  • how to set proxy server details on WebServiceTemplate
  • How can I get a Class object form primitive?
  • How to count rows and Columns of excel sheet in Java
  • Should I split up texture atlas?
  • JavaFX freezing issue
  • What is the JavaFX equivalent of androids AsyncTask?
  • Zenity bash command not working with Java
  • GSON serialize multiple properties to sub object
  • How to convert some elements that satisfy a particular condition in a 2d array into a list in java?
  • Setting LinkedList nodes to null
  • Java Swing ignore text size on JButton
  • Collision detection for separate class instances - Processing Java
  • handle unreal numbers, jump to catch
  • Java - 100 decimal places in variable
  • Cancel previously shown toast before showing new toast
  • projectile motion sim - 'illegal start of type' error
  • How to print out the whole contents of a stack?
  • How to find variable name from a list of class in a package
  • how can i make this dialog close when socket is accepted?
  • I have created a small book program, I am new to java. Can't find what the error or mistake in this code?
  • shadow
    Privacy Policy - Terms - Contact Us © animezone.co