Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 4 of 4

Thread: Java files compilation with java code

  1. #1
    Junior Member
    Join Date
    Jul 2011
    Posts
    2
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Java files compilation with java code

    Hi Friends,

    Can any body please give a sample to compile java files presented inside package from java code.

    Thanks


  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Java files compilation with java code

    What does "inside package" mean? Do you mean the source has a package statement.
    Can you show the layout (folders) of the files and the packages they are in that you are trying to compile?

    from java code.
    Is the javac command to be issued by a java program?

  3. #3
    Junior Member
    Join Date
    Jul 2011
    Posts
    2
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Java files compilation with java code

    Yes, source has package structure.

    for example my package structure is
    src
    --com.example.main -------> contains 2 classes
    --Test1.java
    --Test2.java
    --com.example.util------------->contains 2 classes
    --Util1.java
    --Util2.java

    I need to compile this src using java programe.


    Thanks

  4. #4
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Java files compilation with java code

    Look at the JavaCompiler interface.

    Here are some samples I got from somewhere:
    import java.io.*;
    import java.util.*;
    import javax.tools.*;
    import javax.tools.JavaCompiler.*;
    import java.net.URI;
    import java.lang.reflect.Method;
     
     
    public class JavaCompilationTest3 {
     
    	public static void main(String[] args) throws Exception {
          JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    		DiagnosticCollector<JavaFileObject> diagnosticsCollector =
    			                                            new DiagnosticCollector<JavaFileObject>();
    		StandardJavaFileManager fileManager  =
                                 compiler.getStandardFileManager(diagnosticsCollector, null, null);
          JavaFileObject javaObjectFromString = getJavaFileContentsAsString();
          Iterable<? extends JavaFileObject> fileObjects = Arrays.asList(javaObjectFromString);
     
          CompilationTask task = compiler.getTask(null, fileManager, diagnosticsCollector, null, null, fileObjects);
    		Boolean result = task.call();
     
     
          List<Diagnostic<? extends JavaFileObject>> diagnostics = diagnosticsCollector.getDiagnostics();
     
    		for(Diagnostic<? extends JavaFileObject> d : diagnostics){
    			// Print all the information here.
             System.out.println(d.getMessage(null)); 
    		}
     
    		if(result == true){
    			System.out.println("Compilation has succeeded");
             // Now execute it
             Class tc = Class.forName("TestClass");
    //         System.out.println("tc=" + tc);
             Method[] methods = tc.getDeclaredMethods();
             try {
               Method testMethod = tc.getMethod("testMethod", new Class[]{}); 
             //warning: [unchecked] unchecked call to getMethod(java.lang.String,java.lang.Class<?>...) 
             //as a member of the raw type java.lang.Class
     
               testMethod.invoke(null, new Object[]{});  // Call TestClass's testMethod()
     
             }catch(Exception x) {
               x.printStackTrace();
             }
    		}else{
    			System.out.println("Compilation fails.");
    		}
    	}
     
       //------------------------------------------------------------------
       static class JavaObjectFromString extends SimpleJavaFileObject{
           private String contents = null;
     
           public JavaObjectFromString(String className, String contents) throws Exception{
           		super(new URI(className), Kind.SOURCE);
                this.contents = contents;
           }
           public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException {
           		return contents;
           }
       } // end class
     
    	private static SimpleJavaFileObject getJavaFileContentsAsString(){
    		StringBuilder javaFileContents = new StringBuilder("" +
    				"class TestClass{" +
    				"	public static void testMethod(){" +
    	         "		System.out.println(" + "\" this is a  test message.\"" +           ");" +
    				"}" +
    				"}");
    		JavaObjectFromString javaFileObject = null;
    		try{
             javaFileObject = new JavaObjectFromString("TestClass", javaFileContents.toString());
    		}catch(Exception exception){
    			exception.printStackTrace();
    		}
    		return javaFileObject;
    	} // end class
    }

    // Auto parsing code
    import java.io.*;
    import java.util.*;
    import javax.tools.*;
    import javax.tools.JavaCompiler.*;
    import java.net.URI;
    import java.lang.reflect.Method;
     
     
    // Define classes needed here
    interface TestQuestionSaver {
      public void AddQuestion(Question q);
    }  
     
     
    class Array {
      String[] array;
      Array(String a1, String a2, String a3) {
       array = new String[] {a1, a2, a3};
      }
    } // end class Array
     
    class Question {
      String url, ques, what;
      Array choices;
      int type;
      boolean answer;
      String sAnswer;
     
      public Question(String url, String ques, int type, Array choices, boolean answer, String what){
        this.url = url;
        this.ques = ques;
        this.type = type;
        this.choices = choices;
        this.what = what;
        this.answer = answer;
      }
      public Question(String url, String ques, int type, Array choices, String sAnswer, String what){
        this.url = url;
        this.ques = ques;
        this.type = type;
        this.choices = choices;
        this.sAnswer = sAnswer;
        this.what = what;
      }
    } // end class Question
     
     
    //---------------------------------------------------------------------
    public class TestQuestionParser implements TestQuestionSaver {
     
    // Define the program to compile and execute as a String
       String pgmPart1a = "class ";
       String pgmPart1b =  " {"
          + " public static void addQuestions(TestQuestionSaver test) {\n"
          + "   final int QUESTION_TYPE_CHOICE = 1;\n"
          + "   final int QUESTION_TYPE_TF = 2;\n";
     
             // The code to "parse" goes between these lines of ********s
             //*************************************************************************************************************
       String code = 
              " test.AddQuestion( new Question (\"com.scorm.golfsamples.interactions.etiquette_1\","
              + "                            \"When Another player is attempting a shot, it is best to stand:\"," 
              + "                            QUESTION_TYPE_CHOICE,"
              + "                            new Array(\"On top of his ball\", \"Directly in his line of fire\", \"Out of the player's line of sight\"),"
              + "                            \"Out of the player's line of sight\","
              + "                            \"obj_etiquette\")"
              + "      );\n"
              + " test.AddQuestion( new Question (\"com.scorm.golfsamples.interactions.etiquette_2\","
              + "                            \"Generally sand trap rakes should be left outside of the hazard.\","
              + "                            QUESTION_TYPE_TF,"
              + "                            null,"
              + "                            true,"
              + "                            \"obj_etiquette\")"
              + "      );\n"
              + " test.AddQuestion( new Question (\"com.scorm.golfsamples.interactions.etiquette_3\","
              + "                            \"The player with the best score on the previous hole tees off:\"," 
              + "                            QUESTION_TYPE_CHOICE,"
              + "                            new Array(\"First\", \"Last\", \"With a putter\"),"
              + "                            \"First\","
              + "                            \"obj_etiquette\")"
              + "      );\n";   
     
           //************************************************************************************************ 
           String pgmPart2 = "}\n }";    // wrapup method and class
     
     
     
       //----------------------------------------------
       // Start here
       public static void main(String[] args) {
         new TestQuestionParser();
       }
     
       //----------------------------------------------------------------------------------
       public TestQuestionParser()  {
         // Here create the .java file and compile it and then call its addQuestion method
         String className = "TestQuestions2";      // The name of class we're generating
         String source = pgmPart1a + className + pgmPart1b+ code + pgmPart2;
     
         // Put together the parts necessary to compile the above code
          JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    		DiagnosticCollector<JavaFileObject> diagnosticsCollector =
    			                                            new DiagnosticCollector<JavaFileObject>();
    		StandardJavaFileManager fileManager  =
                                 compiler.getStandardFileManager(diagnosticsCollector, null, null);
          JavaFileObject javaObjectFromString = getJavaFileContentsAsString(className, source);
          Iterable<? extends JavaFileObject> fileObjects = Arrays.asList(javaObjectFromString);
     
          // Compile it
          CompilationTask task = compiler.getTask(null, fileManager, diagnosticsCollector, null, null, fileObjects);
    		Boolean result = task.call();
     
          // Show error messages
          List<Diagnostic<? extends JavaFileObject>> diagnostics = diagnosticsCollector.getDiagnostics();
     
    		for(Diagnostic<? extends JavaFileObject> d : diagnostics){
    			// Print all the information here.
             System.out.println(d.getMessage(null)); 
    		}
     
          // Test results
    		if(result == true){
    			System.out.println("Compilation has succeeded");
             // Now execute it
             try {
               Class tc = Class.forName(className);
    //         System.out.println("tc=" + tc);
               Method[] methods = tc.getDeclaredMethods();
               Method testMethod = tc.getMethod("addQuestions", new Class[]{TestQuestionSaver.class}); 
             //warning: [unchecked] unchecked call to getMethod(java.lang.String,java.lang.Class<?>...) 
             //as a member of the raw type java.lang.Class
     
               testMethod.invoke(null, new Object[]{this});  // Call addQuestions
     
             }catch(Exception x) {
               x.printStackTrace();
             }
    		}else{
    			System.out.println("Compilation fails.");
    		}
     
       } // end constructor
     
       //------------------------------------------------------------------
       class JavaObjectFromString extends SimpleJavaFileObject{
           private String contents = null;
     
           public JavaObjectFromString(String className, String contents) throws Exception{
           		super(new URI(className), Kind.SOURCE);
                this.contents = contents;
           }
           public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException {
           		return contents;
           }
       } // end class
     
    	private SimpleJavaFileObject getJavaFileContentsAsString(String className, String source){
    		StringBuilder javaFileContents = new StringBuilder(source);
    		JavaObjectFromString javaFileObject = null;
    		try{
             javaFileObject = new JavaObjectFromString(className, javaFileContents.toString());
    		}catch(Exception exception){
    			exception.printStackTrace();
    		}
    		return javaFileObject;
    	} // end getJavaFileContensAsString
     
       //------------------------------------------------------------------------------
       // The call-back interface method will get the data from the calls made to it
      public void AddQuestion(Question q) {
         System.out.println("url=" +q. url + ", ques=" + q.ques + "\n   answer=" + q.sAnswer);
      }
    }     
    /*   
    Running: D:\Java\jdk1.6.0_25\jre\bin\java.exe  -Xmx512M -classpath D:\JavaDevelopment;. TestQuestionParser
     
    Compilation has succeeded
    url=com.scorm.golfsamples.interactions.etiquette_1, ques=When Another player is attempting a shot, it is best to stand:
       answer=Out of the player's line of sight
    url=com.scorm.golfsamples.interactions.etiquette_2, ques=Generally sand trap rakes should be left outside of the hazard.
       answer=null
    url=com.scorm.golfsamples.interactions.etiquette_3, ques=The player with the best score on the previous hole tees off:
       answer=First
     
    0 error(s)
    */
    Last edited by Norm; July 14th, 2011 at 08:15 AM.

Similar Threads

  1. By using java how to listout sharing files in LAN...?
    By ram07 in forum Java Networking
    Replies: 4
    Last Post: March 26th, 2011, 10:18 PM
  2. HOW TO UPLOAD JAVA FILES IN NETBEANS
    By ordonezc78 in forum Java IDEs
    Replies: 2
    Last Post: March 19th, 2011, 09:05 AM
  3. HTK files from Java problem.
    By ivanloes in forum Java Theory & Questions
    Replies: 0
    Last Post: December 17th, 2010, 06:49 PM
  4. got all .java files ready. how to make them into jar?
    By sibbe in forum Java Theory & Questions
    Replies: 22
    Last Post: December 6th, 2010, 07:09 PM
  5. Calling exe files from Java
    By linuxrockers in forum What's Wrong With My Code?
    Replies: 3
    Last Post: March 26th, 2010, 04:20 AM