Subclass on the fly


DevX Home    Today's Headlines   Articles Archive   Tip Bank   Forums   

Results 1 to 5 of 5

Thread: Subclass on the fly

  1. #1
    Join Date
    Jul 2005
    Posts
    2

    Subclass on the fly

    I have a based class within my Java application. I would like to add new classes on the fly based on my based class. Is there any way to do it while running the application.

    For example in my program, I have

    class BasedClass {
    private String name;
    BasedClass(String name){ this.name = name;}

    }

    Thanks for any opinion to achieve this.

  2. #2
    Join Date
    Jul 2005
    Posts
    4
    If I understand the question correct, one way to do this can be by extending the BaseClass into an abstract class and dynamically creating the abstract class' implementation / instance.

    eg :

    public abstract class ExtendedAbstract extends BaseClass {

    public abstract void abstractMethod();

    }


    And...

    //create dynamically anywhere in your code.

    ExtendedAbstract dynClass = new ExtendedAbstract(){
    public void abstractMethod(){
    //implementation
    ...
    ...
    }
    };


    .. well if this is what you want.

  3. #3
    Join Date
    Nov 2004
    Location
    Norway
    Posts
    1,560
    If this could be done at all, then how would the already running code be able to use the new classes and invoke their methods ?
    eschew obfuscation

  4. #4
    Join Date
    Jul 2005
    Posts
    2
    I am using the base class to call the corresponding method or use the reflective tool to do it.

    Ideally, I would like to be able to construct a class into a string and have some kind of Java object that will compile the class into byte stream. Once the class is in ByteCode I can then use classloader to load it in and run it.

  5. #5
    Join Date
    Jul 2005
    Posts
    22
    AhHaHaHa!!! I found out how to do it. This question was so inspirational that I had to find a solution, and here it is:

    Code:
    //file: RealTimeClassCreation.java
    import java.io.BufferedReader;
    import java.io.BufferedWriter;
    import java.io.File;
    import java.io.FileWriter;
    import java.io.InputStreamReader;
    import java.net.URL;
    import java.net.URLClassLoader;
    /*
     * ClassCreationMain.java
     *
     * Created on July 27, 2005, 6:49 PM
     */
    
    /**
     * @author Zodoz
     */
    public class ClassCreationMain {
        
        BufferedWriter out;
        
        public ClassCreationMain() throws Exception {
    	BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    	System.out.println("What do you want to say?");
    	String sayWhat = in.readLine();
            //create the source file
    	File f = new File ("SayClass.java");
    	out = new BufferedWriter(new FileWriter(f));
    	write("public class SayClass extends TestSay {");
    	write("\tpublic String getText() {");
    	write("\t\treturn \""+sayWhat+"\";");
    	write("\t}");
    	write("}");
    	out.close();
            /*****************************
             *java source file is created
             *****************************/
    	File f2 = new File ("");
    	URL url = new URL("file:"+f2.getAbsolutePath()+"\\");
    	URLClassLoader loader = new URLClassLoader(new URL[] { url }); //url is location
                                 //that the classes can be found
    	Process p = Runtime.getRuntime().exec("javac -classpath build/classes SayClass.java");  //make sure your system path is setup to run javac
    	/*******************************************
             * use if you want to see any errors:
    	 *
    	 *  BufferedReader pIn = new BufferedReader(new InputStreamReader(p.getErrorStream()));
    	 *  String line = "";
    	 *  while((line = pIn.readLine())!=null)
    	 *      System.out.println(line);
    	 ***********************************/
    	p.waitFor(); //wait to finish the process, this line is a must
    	Class c = loader.loadClass("SayClass");  //load the class
    	Object o = c.newInstance();  //create an instance of that class
    	TestSay ts = (TestSay)o;  //typecast it to the real class that it is
    	System.out.println(ts.getText());  //use it
        }
        
        public void write(String write) throws Exception {
    	out.write(write);
    	out.newLine();
    	out.flush();
        }
        
        public static void main(String args[]) throws Exception {
    	new ClassCreationMain();
        }
    }
    A simple class to test extensions:
    Code:
    /*
     * TestSay.java
     *
     * Created on July 27, 2005, 8:23 PM
     */
    
    /**
     *
     * @author Zodoz
     */
    public abstract class TestSay {
        public abstract String getText();
    }
    Please tell me if this works for you, and please fell free to ask any questions.

Similar Threads

  1. Test Java samples in fly
    By mark9876 in forum Java
    Replies: 0
    Last Post: 03-24-2005, 11:57 PM
  2. Replies: 1
    Last Post: 12-09-2001, 10:09 AM
  3. Replies: 4
    Last Post: 10-27-2000, 09:46 AM
  4. Impossible Mystery? VB subclass drops messages!
    By Matthew Cromer in forum VB Classic
    Replies: 8
    Last Post: 08-04-2000, 12:44 PM
  5. Impossible Mystery? VB subclass drops messages!
    By Matthew Cromer in forum VB Classic
    Replies: 0
    Last Post: 08-04-2000, 09:30 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center
 
 
FAQ
Latest Articles
Java
.NET
XML
Database
Enterprise
Questions? Contact us.
C++
Web Development
Wireless
Latest Tips
Open Source


   Development Centers

   -- Android Development Center
   -- Cloud Development Project Center
   -- HTML5 Development Center
   -- Windows Mobile Development Center