Java.lang.Compiler class in Java
In this tutorial, we will learn about the Compiler class in Java. This class provides support and related services to java-to-native-code compilers.
Declaration
The declaration of java.lang.compiler class is as follows:
public final class Compiler extends Object
Methods
The Compiler class has the following methods:
command(): This method tests the argument type and performs documented operations. The syntax for java.lang.Compiler.command() as follows:
public static boolean command(Object arg)
Here, arg is a compiler-specific argument. The method returns a compiler-specific value and throws a NullPointerException if arg is null.
compileClass(): This method compiles the class passed as the argument. The syntax is as follows:
public static boolean compileClass(Class cl)
Here, cl is the class that is to be compiled. The method returns true if compilation is successful, otherwise false. A NullPointerException is thrown if cl is null.
compileClasses(): This method compiles all the classes that have the same name as the string passed as argument. See the syntax.
public static boolean compileClasses(String s)
Here, compileClasses() takes a string argument and compiles all the classes with the same name as s. On successful compilation, it returns true, or else it returns false. The method throws a NullPointerException if s is null.
enable(): This method causes the compiler to start or resume operation. The syntax is as follows:
public static void enable()
The function takes no parameter and does not return anything.
disable(): This method stops the compiler to perform operations. The syntax is given is as follows:
public static void disable()
The function takes no parameter and does not return anything.
Have a look at the Java program below to understand the working of the above-explained methods.
import java.lang.*;
public class Main{
public static class ExampleClass{
public ExampleClass()
{
}
}
public static void main(String args[])
{
ExampleClass ex = new ExampleClass();
Compiler.enable();
Class cl = ex.getClass();
System.out.println(cl);
Object obj = Compiler.command("javac ExampleClass");
System.out.println(obj);
boolean compiled = Compiler.compileClass(cl);
if(compiled == true)
{
System.out.println("Compilation Successful using compileClass() method.");
}
else
{
System.out.println("Compilation unsuccessful using compileClass() method.");
}
String str = "ExampleClass";
boolean compiled_again = Compiler.compileClasses(str);
if(compiled_again == true)
{
System.out.println("Compilation Successful using compileClasses() method.");
}
else
{
System.out.println("Compilation unsuccessful using compileClasses() method.");
}
Compiler.disable();
}
}Output:
class Main$ExampleClass null Compilation unsuccessful using compileClass() method. Compilation unsuccessful using compileClasses() method.
Also read: How to create object of a Java class?
Leave a Reply