A nasty Problem - Java Code

Few days back, I got a problem in which actually I have to get the fields, constructor and method name from a java class. One can think of using reflection API and the problem is easy to solve, but that is not the case. Reflection API can only be used on class files not Java file. Than a quick idea came into mind to compile the file internally, use reflection and then delete the class file, if user don't want to see it. This is never be a tough job if I use JDK6 JavaCompiler code which is :

import java.io.IOException;

import javax.tools.JavaCompiler;
import javax.tools.ToolProvider;

public class JDK6FirstCompile {
  public static void main(String args[]) throws IOException {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    int results = compiler.run(null, null, null, "HelloWorld.java");
    System.out.println("Success: " + (results == 0));
  }
}


class HelloWorld {
  public static void main(String args[]) {
    System.out.println("Hello, World");
  }
}


But but, I was constraint to use JDK5 or less. So, this JDK6 API is not worth for me :-(. Finally, came up with a small code, which probably can do this in all the case. Hoping it will not lose any generic behavior and run in all cases.

Here is the code:

import java.io.\*;

public class CompileCheck {

public void compileClasses2() {
        try {
            String command = System.getProperty("java.home")+File.separator + ".." + File.separator+"bin"+File.separator+"javac " + "HelloWorld.java";
            System.out.println(command);
            Runtime.getRuntime().exec(command);
    } catch (Exception e) { }
    }


    public static void main(String[] args) {
 
        CompileCheck c = new CompileCheck();
        c.compileClasses2();
    }
}


In place of HelloWorld, I can surely use any path where the java file resides. And off course, I can use \*.java as well :-). Please let me know your opinion or any other method easier than this from which I can get class methods, attributes and all from a java file.

Comments:

Read this as this would help you
http://www.juixe.com/techknow/index.php/2006/12/12/invoke-javac-at-runtime/

Posted by Srikanth on September 16, 2008 at 07:50 AM IST #

o yes, better option. thanks ! just classpath(tools.jar) issue need to be resolved by code too.

Posted by Vaibhav on September 21, 2008 at 05:59 PM IST #

erssdsd

Posted by guest on September 30, 2008 at 10:13 AM IST #

Post a Comment:
Comments are closed for this entry.
About

Hi, I am Vaibhav Choudhary working in Sun. This blog is all about simple concept of Java and JavaFX.

Search

Archives
« July 2014
SunMonTueWedThuFriSat
  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
  
       
Today