Executing class files from a Java App dynamically

Hi!, Is there any way i can execute java .class files from my Java Application dynamically. I know that java uses Dynamic method Invocation. Is that true of class files generated using some other language compiled for the JVM.
In my case i would like to make a Web browser that interprets HTML and also java applets embeded in them. I would like to use the JRE of the platform execute the applets for me rather than writing the code for my Browser to interpret the class files.
Thanks in Advance.

You just need a custom class loader to bring these applets into your JVM.
http://developer.java.sun.com/developer/onlineTraining/Security/Fundamentals/magercises/URLClassLoader/index.html
Then you can use the methods of java.lang.Class to create an instance of such a class. As soon as you have it, you can just treat it as a regular Applet and invoke init(), stop() etc. appropriately.
If you want to execute anything else than conventional Applets, you might consider reflection to find out about methods implemented:
http://java.sun.com/docs/books/tutorial/reflect/index.html

Similar Messages

  • Why do I get multiple class files from 1 java file?

    I wrote a dialog box using gridBagConstraints and another program RunPanel to run it as a java application. For the first time since playing with java, I get multiple class files from a single java file.
    This seems very strange to me and wonder if anyone else has come across this and what could possibly be the reason for it. I did a clean (in Eclipse) just to make sure it wasn't garbage and sure enough they come back again.
    I have ReconPanel.java from which I get ReconPanel.class with the addition of ReconPanel$N.class where N goes from 1 to 5.
    The same thing in RunPanel but here there is only 1 extra file, RunPanel$1.class.
    I'll include the code for RunPanel since it is relatively small:
    package ilan;
    import javax.swing.JFrame;
    public class RunPanel extends JFrame {
         private static final long serialVersionUID = 1L;
         private ReconPanel m_reconPanel = null;
         public RunPanel() {
              super();
              initialize();
          * This method initializes this
         private void initialize() {
            this.setTitle("tester");
            this.setSize(new java.awt.Dimension(138,396));
            this.addWindowListener(new java.awt.event.WindowAdapter() {
                 public void windowClosing(java.awt.event.WindowEvent e) {
                      m_reconPanel.exitPanel();
                      System.exit(0);
              m_reconPanel = new ReconPanel();
              this.getContentPane().add(m_reconPanel);
          * @param args
         public static void main(String[] args) {
              JFrame frame1 = new RunPanel();
              frame1.setVisible(true);
    }  //  @jve:decl-index=0:visual-constraint="10,10"The only thing "unusual" I do is to put a listener on the WindowClosing so that I can go back to ReconPanel and write results to the registry.
    Can anyone tell me what is going on?
    Thanks,
    Ilan

    He IIan,
    Yes, you get number of extra class files based on your number of anomyous class es used. Like in your RunPanel, you get only 1 ..$1.class file, b'coz u have used only 1 annomyous class & i.e WindowAdapter. Take a look at this code :-
    this.addWindowListener(new java.awt.event.WindowAdapter() {
                 public void windowClosing(java.awt.event.WindowEvent e) {
                      m_reconPanel.exitPanel();
                      System.exit(0);
            });Similarly, in your ReconPanel, you must have used such kind of classes 5 times, & hence u get such 5 extra classes. To avoiod such extra classes, if you can directly implement that interface or extend the class, if possible will be best. For example, for each button, u write
    button1.addActionListener(new ActionListener() {
    // Code
    });Instead, of this, its better to implement ActionListener & write
    button1.addActionListener(this);
    public void actionPerformed(ActionEvent ae) {
       if (ae.getSource() == button1) {
       // CODE
       }Likethis, you can get rid of such numerous extra class files. In IDE, if you ask to add actionEvent, it will do the first method. To get rid of it, don't add event in the properties, instead, apply the second method. The same thing applies for anyother event. The first option is worthful, if by implementing, u got to write 5 functions from which u r gonna use just 1 method.
    Hope this clears your question.
    Trupti

  • Problem executing .bat file from within Java class

    I'm stumped: I have no problem executing a .bat file that sets classpaths and executes a Java jar, but when I try to execute other executables first and then the .jar, my application hangs and since the DOS box doesn't come up over my GUI, I can't see what's going on.
    This works:
    public void execute() throws Exception {
    String s = "c:\\cs47auxs\\omnijar\\omni.bat";
    Process p = Runtime.getRuntime().exec("\"" + s + "\"");
    p.waitFor();
    JOptionPane.showMessageDialog(frame,
    "The Database Has Been Successfully Reloaded.",
    "Information Message",
    JOptionPane.INFORMATION_MESSAGE);
    Here's the .bat 'omni.bat'
    set JAVA_HOME=c:\j2sdk1.4.2_04\bin
    %JAVA_HOME%\java -jar C:\CS47AUXS\OMNILOADJAR\OmniLoad.jar
    This doesn't work:
    public void execute() throws Exception {
    String s = "c:\\cs47auxs\\omnijar\\jobomni.bat";
    Process p = Runtime.getRuntime().exec("\"" + s + "\"");
    p.waitFor();
    JOptionPane.showMessageDialog(frame,
    "The Database Has Been Successfully Reloaded.",
    "Information Message",
    JOptionPane.INFORMATION_MESSAGE);
    Here's the .bat file 'jobomni.bat'
    SET NETX_HOME=C:\CS47AUXS
    SET COBOL_HOME=C:\CS47AUXS\OFFLINE
    CD %NETX_HOME%
    CALL SET-NETX.CMD
    CD %COBOL_HOME%
    SSBPPC10 JOBOMNI X
    SET JH=C:\J2SDK1.4.2_04\BIN
    SET OMNI_HOME=C:\CS47AUXS\OMNILOADJAR
    CD %OMNI_HOME%
    %JH%\java -jar omniload.jar
    Can anyone shed some light here? Even when I execute the application from the command line the new DOS box doesn't become visible nor can I see any errors. If I could just get that visibility, I could probably figure out what is going wrong.

    Same problem with me as well.... Badly looking for a solution...
    I predict the following:
    - If your batch file has pretty less number of dos/shell commands then it gets executed fine with exec() and proc.waitFor();
    - If you increase the number of dos/shell commands in the bat file then try executing it then it definately hangs at proc.waitFor();
    Even "cmd.exe /C C:\\test.bat" hangs... if the commands are more...
    Is this some sort of bug? or am i doing anything wrong? I tried searching for solution on the net and search forums... but couldnt find a solution for the same.. not sure where i missed, what i missed...
    Incase some one finds a solution.. do post it here...
    Message was edited by:
    amadas

  • Opening a file from a java app (not applet)

    My program can't find the text file I'm trying to open in my stand-alone java app. I am specifying it like this:
    File filename = new File("myfile.txt");
    FileReader = new FileReader(filename);
    It is in the same directly as the class files. It won't find it when it's in a jar file either. I had a similar problem with an applet a lont time ago, but that turned out to be a security issue, which I assume normal apps don't have.
    So, what's up with this?

    If system become larger, there are duplicated files
    can be found in different directories.
    Using classpath may cause problem, if there are
    duplicated file name.
    If you are coding, you should know exact location of
    the file to be opened.
    "system become larger" - huh? You control the classpath on a per-app basis, not one huge monolithic classpath containing all jars/folders for all apps.
    It's common, well-designed practice to use the classpath. It's bad practice to hard-code directory names and expect all deployments of the app to follow the same directory naming convention. I wouldn't want you to dictate to me where to put the file on my hard drive. I should be able to install it anywhere I want, and let it find it (via the classpath, in this instance).

  • How to execute *.BAT file from  the Java Application

    Hello to all.
    I wants to run *.BAT file form my applicaion.
    Can u give the code of that two-four line,please
    Wating four your replay.
    Yours Friend
    Bhavin Shah.....

    pr = rt.exec("cmd.exe /c start " + yourProgramName)The exec() method executes the command you specify in the argument and returns a process. In this example, it's telling Windows to run "yourProgramName".
    HTH

  • Running the .class file from java code

    I'm doing a kind of providing service like compiling and running Java code on server side and giving output to the end user.
    Please suggest me an approach with code to run .class file from the Java code.
    import java.io.*;
    public class demo {
    public static void main(String args[]) throws IOException, InterruptedException {
    int result;
    try {
    System.out.println("command output:");
    Process proc = Runtime.getRuntime().exec("java -cp . demoh");
    InputStream in = proc.getInputStream();
    result = proc.waitFor();
    BufferedInputStream buffer = new BufferedInputStream(proc.getInputStream());
    BufferedReader commandOutput = new BufferedReader(new InputStreamReader(buffer));
    String line = null;
    System.out.print(commandOutput);
    try {
    while ((line = commandOutput.readLine()) != null) {
    System.out.print(line);
    System.out.println("command output: " + line);
    }//end while
    commandOutput.close();
    } catch (IOException e) {
    //log and/or handle it
    }//end catc
    } catch (IOException e) {
    System.err.println("IOException raised: " + e.getMessage());
    }

    What happened when you tried what you have there?

  • Executing batch file from Java stored procedure hang

    Dears,
    I'm using the following code to execute batch file from Java Stored procedure, which is working fine from Java IDE JDeveloper 10.1.3.4.
    public static String runFile(String drive)
    String result = "";
    String content = "echo off\n" + "vol " + drive + ": | find /i \"Serial Number is\"";
    try {
    File directory = new File(drive + ":");
    File file = File.createTempFile("bb1", ".bat", directory);
    file.deleteOnExit();
    FileWriter fw = new java.io.FileWriter(file);
    fw.write(content);
    fw.close();
    // The next line is the command causing the problem
    Process p = Runtime.getRuntime().exec("cmd.exe /c " + file.getPath());
    BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
    String line;
    while ((line = input.readLine()) != null)
    result += line;
    input.close();
    file.delete();
    result = result.substring( result.lastIndexOf( ' ' )).trim();
    } catch (Exception e) {
    e.printStackTrace();
    result = e.getClass().getName() + " : " + e.getMessage();
    return result;
    The above code is used in getting the volume of a drive on windows, something like "80EC-C230"
    I gave the SYSTEM schema the required privilege to execute the code.
    EXEC DBMS_JAVA.grant_permission('SYSTEM', 'java.io.FilePermission', '<<ALL FILES>>', 'read ,write, execute, delete');
    EXEC DBMS_JAVA.grant_permission('SYSTEM', 'SYS:java.lang.RuntimePermission', 'writeFileDescriptor', '');
    EXEC DBMS_JAVA.grant_permission('SYSTEM', 'SYS:java.lang.RuntimePermission', 'readFileDescriptor', '');
    GRANT JAVAUSERPRIV TO SYSTEM;
    I have used the following to load the class in Oracle 9ir2 DB:
    loadjava -u [system/******@orcl|mailto:system/******@orcl] -v -resolve C:\Server\src\net\dev\Util.java
    CREATE FUNCTION A1(drive IN VARCHAR2) RETURN VARCHAR2 AS LANGUAGE JAVA NAME 'net.dev.Util.a1(java.lang.String) return java.lang.String';
    variable serial1 varchar2(1000);
    call A1( 'C' ) into :serial1;
    The problem that it hangs when I execute the call to the function (I have indicated the line causing the problem in a comment in the code).
    I have seen similar problems on other forums, but no solution posted
    [http://oracle.ittoolbox.com/groups/technical-functional/oracle-jdeveloper-l/run-an-exe-file-using-oracle-database-trigger-1567662]
    I have posted this in JDeveloper forum ([t-853821]) but suggested to post for forum in DB.
    Can anyne help?

    Dear Peter,
    You are totally right, I got this as mistake copy paste. I'm just having a Java utility for running external files outside Oracle DB, this is the method runFile()
    I'm passing it the content of script and names of file to be created on the fly and executed then deleted, sorry for the mistake in creating caller function.
    The main point, how I claim that the line in code where creating external process is the problem. I have tried the code with commenting this line and it was working ok, I made this to make sure of the permission required that I need to give to the schema passing security permission problems.
    The function script is running perfect if I'm executing vbs script outside Oracle using something like "cscript //NoLogo aaa1.vbs", but when I use the command line the call just never returns to me "cmd.exe /c bb1.bat".
    where content of bb1.bat as follows:
    echo off
    vol C: | find /i "Serial Number is"
    The above batch file just get the serial number of hard drive assigned when windows formatted HD.
    Same code runs outside Oracle just fine, but inside Oracle doesn't return if I exectued the following:
    variable serial1 varchar2(1000);
    call A1( 'C' ) into :serial1;
    Never returns
    Thanks for tracing teh issue to that details ;) hope you coul help.

  • How can I execute a batch file from my java program

    Hi,
    Can someone help me or direct me to a link,
    How can I execute a DOS batch file from my java program?
    Thanks

    You will need to grab a handle to the process's
    outputstream so u can see its output.The OP didn't mention any output from any batch file;
    nor any input for that
    matter,so lets not complicate matters here for now
    ok?Actually I think this is essential to see whether it works or not. It's either that or do some manual check to see whether it ran, which is not exactly elegant, and in some cases this may not be easier than simply writing the output stream code, or in fact it may be impossible to check manually.
    I'm sure it wasn't intentional that your post appeared to be bristling with attitude.

  • How to create windows executable file from a java file. Please help.

    Hi,
    For my project I developed the codes in Java. It is working well with java run time environment. But without that I can not run it. I need to create a exe file (windows executable file) from the java source code. If you have any idea please share it with me.
    Even if you know it very lightly, please help with what you know. That would be a big help for me.
    Thank you very much.

    Does anybody know how to read a manual?
    Matt Richardson
    Certified LabVIEW Developer
    MSR Consulting, LLC

  • Trying to compile a .java file from another .java file

    Hello,
    I'm trying to compile a .java file from another .java file using Runtime.exec...
    String c[]=new String[3];
    c[0]="cmd.exe"; c[1]="/c" ; c[2]="javac Hello.java";
    Process p=Runtime.exec(c);
    If anyone can help me in atleast getting the command prompt when Runtime.exec("cmd.exe") is executed...that would be great...I tried out notepad.exe, calc, explorer instead of cmd.exe...all the commands display their respective windows..except cmd.exe...the command prompt doesnt appear...
    Please help me ASAP....
    Thanks for your help in advance...
    Regards.
    AKhila.

    try this. ur code will be compliled and will get .class file. but console won't appear. is it a must for u?
    public class Exec{
         public static void main(String a[]) throws Exception{
              String c[]=new String[3];
              c[0]="cmd.exe"; c[1]="/c" ; c[2]="javac Hello.java";
              Process p=Runtime.getRuntime().exec(c);
              // or Runtime.getRuntime().exec("javac Hello.java");

  • Tomcat6 does not load class files from WEB-INF/lib/myjarfile.jar  WHY???

    I have placed my jar file in c:\tomcat6\webapps\my-application\WEB-INF\lib\myjarfile.jar
    But, after restarting tomcat6, when i try to import the class file contained in the myjarfile.jar in a servlet, it says
    ProcessFileUpload.java:4: package test.test1 does not exist
    import test.test1.*;
    ^It clearly tomcat's class loading problem.
    As i unzipped my jar and placed the packagefolder structure to
    c:\tomcat6\webapps\my-application\WEB-INF\classes\testand it works perfectly.
    Anyone knows its workaround? please suggest if any configuration changes is required in tomcat or so.
    Thanks.
    ---Sujoy

    Thank you gimbal2 . There was error in creating the jar file myjarfile.jar.
    But, now I have created it again and placed it in place
    c:\tomcat6\webapps\my-application\WEB-INF\lib\myjarfile.jarand tried to use one on the Class file included within the jar to compile my servlet. But, still I am getting error at servlet compilation time. I want to place executable jar files in
    c:\tomcat6\webapps\my-application\WEB-INF\lib\myjarfile.jar and compile my servlet and execute the servlet.
    I DO NOT WANT TO unzip the jar, placing all unzipped files to
    c:\tomcat6\webapps\my-application\WEB-INF\classes\ folder and comiple my servlet and execute the servlet. But, I am failing to user WEB-INF\lib\ folder facility....please help me why i am not getting class files from WEB-INF\lib\ folder.
    If you please see the small code bit and tell me any possible error that would be very helpful.
    Step 1: my library java file MyClass.java
    package test.test1;
    public class MyClass {
         String myName = "Default return string value";
         public void setMyName(String varName) {
              this.myName = varName;
         public String getMyName() {
              return this.myName;
    }Step2 : Creating jar file of my library class files
    C:\jdk1.6\bin>jar cvf myjarfile.jar test
    added manifest
    adding: test/(in = 0) (out= 0)(stored 0%)
    adding: test/test1/(in = 0) (out= 0)(stored 0%)
    adding: test/test1/MyClass.class(in = 452) (out= 296)(deflated 34%)
    adding: test/test1/MyClass.java(in = 230) (out= 140)(deflated 39%)
    C:\jdk1.6\bin>Step3 : Double checking the created jar file content by listing its content
    C:\jdk1.6\bin>jar tf myjarfile.jar
    META-INF/
    META-INF/MANIFEST.MF
    test/
    test/test1/
    test/test1/MyClass.class
    test/test1/MyClass.java
    C:\jdk1.6\bin>Step4 : Placed myjarfile.jar to
    c:\tomcat6\webapps\my-application\WEB-INF\lib\Step5 : Restarted standalone Tomcat6 in my Windows XP SP2.
    Step6 : Created a simple servlet LibFolderTest.java within my-application\WEB-INF\classes\ folder with code
    import java.io.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import test.test1.*;
    public class LibFolderTest extends HttpServlet {
         public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
              response.setContentType("text/html");
              PrintWriter out = response.getWriter();
              MyClass mc = new MyClass();
              out.println(mc.getMyName());
    }Step7 : Tried to compile my servlet LibFolderTest.java and got the following error
    LibFolderTest.java:4: package test.test1 does not exist
    import test.test1.*;
    ^
    LibFolderTest.java:11: cannot find symbol
    symbol  : class MyClass
    location: class LibFolderTest
                    MyClass mc = new MyClass();
                    ^
    LibFolderTest.java:11: cannot find symbol
    symbol  : class MyClass
    location: class LibFolderTest
                    MyClass mc = new MyClass();
                                     ^
    3 errorsThe above servlet compilation error on Step7 is telling me that myjarfile.jar is not loaded by Tomcat6 or not available for use when compiling servlet. I want to use myjarfile.jar from within WEB-INF\lib\ folder but I can not. please help.
    ---Sujoy

  • Opening a document from a Java app

    I need to open a document from my Java app. It is a .rtf file and I would like it to open with the system associated application for rtf files. How should I do that?
    I have tried to figure out the Runtime.exec(), but it doesn't do what I need. I have been able to open Notepad or WordPad (oh, yes, I am on a Win XT system) by specifying them in the exec function, but I can't find info on how to let the system choose the program.
    Thanks for your help.
    Wayne

    Take a look at the JDIC project
    https://jdic.dev.java.net/
    In particular the org.jdesktop.jdic.filetypes.AssociationService class
    https://jdic.dev.java.net/nonav/documentation/javadoc/0.9/index.html

  • Executing .CLASS file

    Hello,
    I recently had my machine reimaged and I'm trying to configure it to execute Java class files from the command prompt. After manipulating the PATH and CLASSPATH system variables I was able to get it to the point where I can compile .JAVA source code, but I still can't execute the file.
    The source is named NotesExport.java. I can issue the javac NotesExport.java command successfully, but when I issue java NotesExport, it gives the following error:
    Can't find class NotesExport
    I've confirmed that the NotesExport.class file is indeed there so I'm confused as to why it can't be found.
    Does anyone know what's wrong here?

    Yes, the problem is with the import line below:
    import lotus.notes.*;
    public final class NotesExport extends NotesThread{ <rest of code> }I was told that in order for the import command above to work, I need to add the path to the notes.jar file in my classpath (c:\notes\notes.jar). I've done that, but it still doesn't work. I get the following error messages when I compile this code in JCreator:
    --------------------Configuration: JDK version 1.1.8 <Default>--------------------
    C:\SasJava\NotesExport.java:9: Package lotus.notes not found in import.
    import lotus.notes.*;
           ^
    C:\SasJava\NotesExport.java:11: Superclass NotesThread of class NotesExport not found.
    public final class NotesExport extends NotesThread{
                                           ^
    2 errors
    Process completed.I'm assuming that the NotesThread class is bundled into that notes.jar file, but I'm not sure. I'm also not sure what that lotus.notes.* is all about... I figured that package was part of the notes.jar file too. Since it apparently isn't finding the notes.jar file, even though I tell it where it is in my CLASSPATH, nothing is working!

  • Executing Batch files from Runtime.getRuntime().exec

    Can we execute batch files from Runtime.getRuntime().exec() method.
    Regards,
    Nalini

    hi,
    import java.io.IOException;
    class BatchFileTest{
         public static void main(String args[]){
              try{
              Runtime r = Runtime.getRuntime();
              Process p = r.exec("startcmd.bat");
              catch(IOException en){
                   en.printStackTrace();
    -Regards
    Manikantan

  • How to restrict the .class file from decompilation

    Hi all,
    i got a security problem. i need all the java class files to be most secured. is there any to restriction on the java class files from decompilation. is that possible?. pls help me out. it's very urgent
    thanks in advance

    You can make it harder to understand the decompiled code if you use an obfuscator. (I don't have links to any, do a google search, or search these forums, it have been discussed here previously.)
    You cannot completely prevent decompilation, though. Obfuscating does not for example not mean that any passwords you have hardcoded in the source is secure.

Maybe you are looking for

  • Code in abap query

    hi. i need to create an ABAP/sap query. when i created the InfoSet i used logical db-pnp. if i want to get only the employees which entered my organization during the last month where should i add the ABAP code, under which section => extras -> code.

  • Can I run Adobe CS 5 in Mavericks? Yosemite?

    A friend has Adobe CS 5 on disc and would let me use it on my iMac (mid 2011) freshly running Mavericks.  Will this work?  Will it continue to work if I upgrade to Yosemite?  Of course, my rather old software from the first Creative Suite, designed f

  • How to view resolution (ppi/dpi) and bit depth of an image

    Hello, how can I check the native resolution (ppi/dpi) and bit depth of my image files (jpeg, dng and pef)? If it is not possible in lighroom, is there a free app for Mac that makes this possible? Thank you in advance!

  • I want to use a clip for idvd

    I want to use a clip for idvd for the menu so I want only a part of the clip ( in mark & out mark) is there a way to export or creat a copy for capture scratch only the part of the clip I marked?

  • Multiple Outputs One Input

    Hi, I have about four labview files which have outputs that must go into a single VI with only one input. The problem I have is labview will not let you wire multiple sources into a single sink. I have a state machine setup where it goes through a it