Following is an example for the above mentioned methods.
By Using java.lang.Compiler.command()
CompilerDemo.java
[java]
package com.SPlessons;
import java.lang.*;
public class CompilerDemo {
public static void main(String[] args) {
CompilerDemo cls = new CompilerDemo();
CompilerDemo subcls = new SubClass1();
// class CompilerDemo
Class c = cls.getClass();
System.out.println(c);
// sub class SubClass1
Class c1 = subcls.getClass();
System.out.println(c1);
/* Let's compile CompilerDemo class using command method */
Object retval = Compiler.command("javac CompilerDemo");
System.out.println("Return Value = " + retval);
}
}
class SubClass1 extends CompilerDemo {
// sub class
}
[/java]
Here the program is going to compile by using a command which specified in the code(
javac CompilerDemo
) that as follows.
[java]Object retval = Compiler.command("javac CompilerDemo");[/java]
As discussed in the above description java.lang Compiler Class uses the methods of
java.lang.Object.getClass()
, getClass() is the method of Object class that is used to return the run time class of an object.
Output: Now compile the code result will be as follows.
[java]
class com.SPlessons.CompilerDemo
class com.SPlessons.SubClass1
Return Value = null
[/java]
By Using java.lang.Compiler.compileClass()
Now instead of the command line code place the
boolean retval = Compiler.compileClass(c1);
.
Output: Following is the result will be displayed.
[java]
class com.SPlessons.CompilerDemo
class com.SPlessons.SubClass1
Return Value = false[/java]
By Using java.lang.Compiler.compileClasses()
Now instead of command line code place the following code, where the developer created a string that is "CompilerDemo".
[java]
/* returns false if the compilation failed or no compiler is
available */
String str = "CompilerDemo";
boolean retval = Compiler.compileClasses(str);
[/java]
Output: If compilation failed then it returns false as follows.
[java]
class com.SPlessons.CompilerDemo
class com.SPlessons.SubClass1
Return Value = false[/java]