4

Is it possible to create a new Java file from an existing Java file after changing some of its attributes at runtime?

Suppose I have a java file

public class Student {
    private int rollNo;
    private String name;
    // getters and setters
    // constructor
}

Is it possible to create something like this, provided that rollNo is a key element for the table?

public class Student {
    private StudentKey key;
    private String name;
    //getters and setters
    //constructor
}

public class StudentKey {
    private int rollNo;
    // getters and setters
    // construcotors
}

Please help. Thanks.

Patrick
  • 1,717
  • 7
  • 21
  • 28
M.J.
  • 16,266
  • 28
  • 75
  • 97
  • Hint:To answer ur Q? First of all think in this way like can a class be created at run time. because every class needs to be load, compile and then run.Can this possible at run time only? – Shashank T Jun 05 '10 at 13:11
  • @javauser: You can do this at runtime with the Java Compiler API (see [this previous answer](http://stackoverflow.com/questions/2130039/javacompiler-from-jdk-1-6-how-to-write-class-bytes-directly-to-byte-array/2130290#2130290)). This doesn't apply here (at least not alone) because the OP wants to modify an already compiled/loaded type. But to strictly answer your question, it is possible. – Pascal Thivent Jun 05 '10 at 13:21
  • 1
    @javauser: please make only relevant comments. No riddles, thanks. In addition to that, "eleet speak", like your *"To answer ur Q?"* is frowned on SO. Please refrain from doing so. – NoozNooz42 Jun 05 '10 at 15:46

1 Answers1

4

Take a look at javassist.

Rhangaun
  • 1,430
  • 2
  • 15
  • 34