Compiling a .java at runtime

hi,
i have program that generates a java class and write's this class into a file.
how can i compile this class to load it later in the program ?
i would prefer a solution without writing the .java file ;-)
Dirk

yes, use com.sun.tools.javac.Main class. Usage is:
com.sun.tools.javac.Main compiler = new com.sun.tools.javac.Main();
int returnCode = compiler.compile("your_java_file");The method compile(String[] args) accept the same args as javac, and in fact, javac itself invoke a JVM and run com.sun.tools.javac.Main class (this may explain why javac is so slowly).
Anyway, take a look at the com.sun.tools.javac package, you can find more. (say you'll find that the compiler is actually in the package com.sun.tools.javac.v8 package).

Similar Messages

  • Compile java at runtime

    Is it possible that a java program compiles a java source file and (if there are no errors) runs the class file?
    example:
    We need this for scenarios:
    a java program will create java code that will represent a scenario. This class will give the java code to the scenario runner, the scenario runner needs to compile the code and run it.
    thanks,
    frederic

    Hi,
    Is it possible that a java program compiles a java source file and (if there are no errors) runs the >>class file?Yes this can be done you will have to follow the following logic
    1)Create a process which will compile the source code
    2)Once the process has done the compiling and had succeed then call step 3
    3)Create a process which will run the java program
    For this you can use java.lang.Runtime,java.lang.Process class etc
    try this way
    java.lang.Process process=java.lang.Runtime().getRuntime();
    process.exec("c:\\jdk1.3\\bin\\javac c:\\test.java");
    Trace the Error Stream of the process,which can tell you about the status of compilation
    read that and proceed,ie if error is found dont run the code otherwise :
    process.exec("c:\\jdk1.3\\bin\\java test");
    I have not tried this but I believe this can be helpful for you.
    regards vickyk

  • 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");

  • How to compile in Java Source???

    Hello,
    I'm studying a way to compile java files to class files in the java source. I have use the sun.tools.javac.Main to do this, but I have noticed that it aint recomended to use. I also wan't to get the possible errors from the compiler (if java file was wrongly made). The problem using the sun.tools.javac.Main is that it won't guarantee that it works in every platform or in future releases of JDK. Does the JDK 1.4 even support it? (My IDE environment prevents to use JDK 1.4). So the question is: is there a way to compile on the fly (to memory or to class files)? Do I really have to run some external process that compiles the file and then try to get somehow possible errors? That seems to me litle too indecent to use. Any suggestions?
    Thanks,
    Petri Tuomaala

    Hi guys,
    I have also needed to compile Java source from within a Java application. Here is the best solution I came up with:
    Process proc = Runtime.getRuntime().exec( "
    C:\\Temp\\Jikes -bootclasspath C:\\jdk\\jre\\lib\\rt.jar C:\\Java\\com\\sts\\utility\\Utility.java" );
    BufferedReader br = new BufferedReader( new InputStreamReader( proc.getErrorStream() ) );
    String line = null;
    while( (line = br.readLine()) != null ) {
    System.out.println( line );
    proc.waitFor();
    I used Jikes http://oss.software.ibm.com/developerworks/opensource/jikes/ because it compiled my source quicker than Javac did - 250 millseconds for Jikes compared to 2750 milliseconds for Javac.

  • Error while compiling VO  java files

    I am getting following error while compiling VO java class in my instance
    Exception in thread "main" java.lang.ClassFormatError: com.sun.tools.javac.main.Main (erroneous method access flags)
    at JvClassReader.throw_class_format_error(byte) (/usr/lib/libgcj.so.5.0.0)
    at JvClassReader.handleMethod(int, int, int, int) (/usr/lib/libgcj.so.5.0.0)
    at JvClassReader.read_methods() (/usr/lib/libgcj.so.5.0.0)
    at JvClassReader.parse() (/usr/lib/libgcj.so.5.0.0)
    at JvDefineClass(java.lang.Class, byte[], int, int) (/usr/lib/libgcj.so.5.0.0)
    at java.lang.VMClassLoader.defineClass(java.lang.ClassLoader, java.lang.String, byte[], int, int, java.security.ProtectionDomain) (/usr/lib/libgcj.so.5.0.0)
    at java.lang.ClassLoader.defineClass(java.lang.String, byte[], int, int, java.security.ProtectionDomain) (/usr/lib/libgcj.so.5.0.0)
    at java.security.SecureClassLoader.defineClass(java.lang.String, byte[], int, int, java.security.CodeSource) (/usr/lib/libgcj.so.5.0.0)
    at java.net.URLClassLoader.findClass(java.lang.String) (/usr/lib/libgcj.so.5.0.0)
    at gnu.gcj.runtime.VMClassLoader.findClass(java.lang.String) (/usr/lib/libgcj.so.5.0.0)
    at java.lang.ClassLoader.loadClass(java.lang.String, boolean) (/usr/lib/libgcj.so.5.0.0)
    at JvFindClass(_Jv_Utf8Const, java.lang.ClassLoader) (/usr/lib/libgcj.so.5.0.0)
    at java.lang.Class.forName(java.lang.String, boolean, java.lang.ClassLoader) (/usr/lib/libgcj.so.5.0.0)
    at JvBytecodeVerifier.verify_instructions_0() (/usr/lib/libgcj.so.5.0.0)
    at JvVerifyMethod(_Jv_InterpMethod) (/usr/lib/libgcj.so.5.0.0)
    at JvPrepareClass(java.lang.Class) (/usr/lib/libgcj.so.5.0.0)
    at JvWaitForState(java.lang.Class, int) (/usr/lib/libgcj.so.5.0.0)
    at java.lang.VMClassLoader.linkClass0(java.lang.Class) (/usr/lib/libgcj.so.5.0.0)
    at java.lang.VMClassLoader.resolveClass(java.lang.Class) (/usr/lib/libgcj.so.5.0.0)
    at java.lang.Class.initializeClass() (/usr/lib/libgcj.so.5.0.0)
    at java.lang.Class.forName(java.lang.String, boolean, java.lang.ClassLoader) (/usr/lib/libgcj.so.5.0.0)
    at java.lang.Class.forName(java.lang.String) (/usr/lib/libgcj.so.5.0.0)
    at gnu.gcj.runtime.FirstThread.run() (/usr/lib/libgcj.so.5.0.0)
    at JvThreadRun(java.lang.Thread) (/usr/lib/libgcj.so.5.0.0)
    at JvRunMain(java.lang.Class, byte const, int, byte const, boolean) (/usr/lib/libgcj.so.5.0.0)
    at __libc_start_main (/lib/tls/libc-2.3.4.so)
    Please advise me to get rid of this one.
    -- Manoj
    Edited by: 856261 on May 4, 2011 12:55 AM

    I created custom VO and files in my local JDev and it is working properly.
    I wanna migrate it to actual instance.So my question is is it mandatory to compile custom java file in application server or i can use same which i used in my local machine(windows)?
    -- Manoj

  • How to compile a java source from a java program

    Hi .
    I would like to know how to compile my java source from inside an execution of a java program.
    Is there another way than rather use :
    Runtime.getRuntime().exec("javac myFile"); ?

    you can and cann't use the source code of javac... or maybe use jikes...

  • Is java.util.Runtime singleton

    Hi,
    Is java.util.Runtime a Singleton class ?
    -Shishir

    \j2sdk1.4.2\jre\lib\rt.jar
    GoF was copyrighted in 1995.
    Java was released in March of 1995. And Runtime wasin it.
    It is a singleton, it just wasn't based on thepattern, largely because the pattern didn't exist
    yet. Sort of...
    OK.
    But when did \j2sdk1.4.2\jre\lib come out? ( :-D,
    I've no memory for date)
    From the Decompiled code,
    can we now safely say it's based upon Singleton
    pattern? for \j2sdk1.4.2\jre\lib?
    What are you talking about?
    Runtime existed in java 1.0. It is pointless to discuss what is in 1.4.2 in this context.
    Do you mean there is no conclusive evidence for
    Singleton pattern?Huh?
    I suspect you do not understand the intent of patterns in GoF.
    Patterns in GoF were not added unless there was existing functionality at the time that supported the contention that a pattern existed and was being used.
    Just because someone doesn't use the GoF book doesn't mean that they are not creating code that uses the patterns that the GoF book collected.
    Likewise I can write a compiler without ever having read the Dragon book.
    So despite the likelyhood that Runtime was not developed using GoF that does not mean that it isn't a singleton.

  • "Error while registering the Java 2 Runtime Environment registry keys"

    "Error while registering the Java 2 Runtime Environment registry keys"
    I am getting the above error when trying to install the 1.3 JRE (installed with the 1.3 plug in which I need). As part of my development I have been installing and uninstalling the JRE multiple times. Then, I got the above error when trying to install it, and now it appears to be installed but I cannot uninstall it. When I try to uninstall it, it just remains, and when I try to install it again I get the above error. I have tried cleaning up all javasoft registry entries, but it doesnt seem to have helped. Can anyone help me either completely uninstall the JRE so I can do a clean install or help me get rid of the error above when I install. Is there some registry entries I should be looking at? Anything else? this is quite urgent as I need to test my applet with the plugin installed and not installed - and I currently cant uninstall it. Any ideas?
    Thanks for your help
    Aaron

    I am getting this same error message when trying to upgrade from 1.3.1_03 to 1.3.1_19.
    I have multiple versions of jre's and jdks on my machine.
    Anyone else seen this problem or know how to resolve it.

  • My class only compiles in Java 1.6 and not in Java 1.5

    Hi, my java class wont compile in java 1.5, it only compiles in Java 1.6. How can i compile the following?
    import java.util.*;
    public class ShoppingBasket
         Vector products;
         public ShoppingBasket() { products = new Vector(); }
         public void addProduct(Product product)
         boolean flag = false;
         for(Enumeration e = getProducts(); e.hasMoreElements();)
              { Product item = (Product)e.nextElement();
                   if(item.getId().equals(product.id))
                   {flag = true; item.quantity++; break; }
              if(!flag){ products.addElement(product);}
         public void deleteProduct(String str)
              for(Enumeration e=getProducts();
              e.hasMoreElements();)
              { Product item = (Product)e.nextElement();
                   if(item.getId().equals(str))
                   {products.removeElement(item); break; }
         public void emptyBasket(){products = new Vector();}
         public int getProductNumber(){ return products.size();}
         public Enumeration getProducts() { return products.elements(); }
         public double getTotal()
         Enumeration e = getProducts();
         double total; Product item;
         for(total=0.0D;e.hasMoreElements();     total+= item.getTotal())
         {item = (Product)e.nextElement(); }
         return total;
    }It should link with a class called Product which compiles fine... the errors i get are below:
    K:\jakarta-tomcat-5.0.18\webapps\ROOT\WEB-INF\classes\ShoppingBasket\ShoppingBas
    ket.java:6: cannot find symbol
    symbol  : class Product
    location: class ShoppingBasket
            public void addProduct(Product product)
                                   ^
    K:\jakarta-tomcat-5.0.18\webapps\ROOT\WEB-INF\classes\ShoppingBasket\ShoppingBas
    ket.java:10: cannot find symbol
    symbol  : class Product
    location: class ShoppingBasket
                    { Product item = (Product)e.nextElement();
                      ^
    K:\jakarta-tomcat-5.0.18\webapps\ROOT\WEB-INF\classes\ShoppingBasket\ShoppingBas
    ket.java:10: cannot find symbol
    symbol  : class Product
    location: class ShoppingBasket
                    { Product item = (Product)e.nextElement();
                                      ^
    K:\jakarta-tomcat-5.0.18\webapps\ROOT\WEB-INF\classes\ShoppingBasket\ShoppingBas
    ket.java:20: cannot find symbol
    symbol  : class Product
    location: class ShoppingBasket
                    { Product item = (Product)e.nextElement();
                      ^
    K:\jakarta-tomcat-5.0.18\webapps\ROOT\WEB-INF\classes\ShoppingBasket\ShoppingBas
    ket.java:20: cannot find symbol
    symbol  : class Product
    location: class ShoppingBasket
                    { Product item = (Product)e.nextElement();
                                      ^
    K:\jakarta-tomcat-5.0.18\webapps\ROOT\WEB-INF\classes\ShoppingBasket\ShoppingBas
    ket.java:35: cannot find symbol
    symbol  : class Product
    location: class ShoppingBasket
            double total; Product item;
                          ^
    K:\jakarta-tomcat-5.0.18\webapps\ROOT\WEB-INF\classes\ShoppingBasket\ShoppingBas
    ket.java:36: inconvertible types
    found   : <nulltype>
    required: double
            for(total=0.0D;e.hasMoreElements();     total+= item.getTotal())
                                                                         ^
    K:\jakarta-tomcat-5.0.18\webapps\ROOT\WEB-INF\classes\ShoppingBasket\ShoppingBas
    ket.java:37: cannot find symbol
    symbol  : class Product
    location: class ShoppingBasket
            {item = (Product)e.nextElement(); }
                     ^
    8 errors

    fahafiz wrote:
    ah, so should i put the classes into the folder which the classpath is assigned to?More likely you should assign your classpath to whatever folder your classes are in.
    Put your files where they make sense, and then fill in classpath accordingly:
    javac -classpath classpath MyFile.java(I think, it's been a while since I compiled from the command-line, see http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/javac.html)

  • Java Proxy Runtime:  failure to locate proxy bean on inbound call

    Hello gurus of the SDN,
    I have been trying to get an inbound Java Proxy scenario to work in XI 3.0 but have not been able to get the JPR to recognize my generated and deployed java code.  My scenario is set up to call the java proxies generated from a message interface based on the MATMAS Idoc.  I successfully deployed the generated java proxies on the same host box as is running the XI instance.  The objects are named as follows
    Message interface on XI = Inbound_MATMAS04
    Generated proxy bean = Inbound_MATMAS04_PortTypeBean
    Implementing class = InboundMATMAS04_PortTypeImpl
    Implementing method = inboundMATMAS04
    I used the JPR transport servlet to register the interface and implementing class but am not sure if I did this correctly.  I used the following entry in my web browser:
    http://nadcp786:50000/ProxyServer/register?
    ns=urn:xiTrainingLabs:groupXX:SAP&
    interface=InboundMATMAS04&
    bean=InboundMATMAS04_PortTypeImpl&
    method=inboundMATMAS04
    I also tried using the localejb/ prefix for the bean name in the above step since the code is co-located.  When I trigger the scenario, the Idoc info is passed into XI and the Java Proxy Runtime is called, but I get the following error response back in the SOAP header:
    - <SAP:Error xmlns:SAP="http://sap.com/xi/XI/Message/30" xmlns:SOAP="http://schemas.xmlsoap.org/soap/envelope/" SOAP:mustUnderstand="1">
      <SAP:Category>XIAdapterFramework</SAP:Category>
      <SAP:Code area="PARSING">GENERAL</SAP:Code>
      <SAP:P1 />
      <SAP:P2 />
      <SAP:P3 />
      <SAP:P4 />
      <SAP:AdditionalText>com.sap.aii.af.ra.ms.api.DeliveryException: Cannot locate proxy bean InboundMATMAS04_PortTypeImpl: com.sap.aii.proxy.xiruntime.core.XmlInboundException: Cannot locate proxy bean InboundMATMAS04_PortTypeImpl</SAP:AdditionalText>
      <SAP:ApplicationFaultMessage namespace="" />
      <SAP:Stack />
      <SAP:Retry>M</SAP:Retry>
      </SAP:Error>
    Finally, appended at the end of this post is the audit log of the messaging system showing that the JPR is called but without being able to locate the bean.  I think I am missing a configuration step somewhere, but can’t figure out what it is!!  Can anyone help me? 
    Many thanks in advance.
    Regards,
    Nick Simon
    Time Stamp     Status     Description
    2004-10-25 19:47:32     Success     The message was successfully received by the messaging system. Profile: XI URL: http://nadcp786.bcsdc.lexington.ibm.com:50000/MessagingSystem/receive/JPR/XI
    2004-10-25 19:47:32     Success     Using connection JPR. Trying to put the message into the receive queue.
    2004-10-25 19:47:32     Success     The message was successfully retrieved from the receive queue.
    2004-10-25 19:47:32     Success     The message status set to DLNG.
    2004-10-25 19:47:32     Success     Java proxy runtime (JPR) accepted the message
    2004-10-25 19:47:34     Error     JPR could not process the message. Reason: Cannot locate proxy bean localejbs/InboundMATMAS04_PortTypeImpl
    2004-10-25 19:47:34     Error     Delivery of the message to the application using connection JPR failed, due to: Cannot locate proxy bean localejbs/InboundMATMAS04_PortTypeImpl.
    2004-10-25 19:47:34     Error     The message status set to FAIL.
    2004-10-25 19:47:34     Error     Asynchronous error detected: Cannot locate proxy bean localejbs/InboundMATMAS04_PortTypeImpl. Trying to report it.
    2004-10-25 19:47:34     Error     Asynchronous error reported.
    Message was edited by: Nicholas Simon

    Hi
    How do you determine the JNDI naming of the a EJB?
    I have following entry in JNDI directory in the root
    Object Name FlightQueryIn
    Class Name javax.naming.Reference
    Context Name 
    Object Value Reference Class Name:
    Type: clientAppName
    Content: sap.com/JavaProxyEAR
    Type: interfaceType
    Content: remote
    Type: home
    Content: com.sap.aii.proxy.xiruntime.core.AbstractProxyInboundHome4
    Type: ejb-link
    Content: FlightSeatAvailabilityQueryIn_PortTypeBean
    Type: jndi-name
    Content: FlightQueryIn
    Type: remote
    Content: com.sap.aii.proxy.xiruntime.core.AbstractProxyInboundRemote4
    I tried to register the bean with JPR using:
    http://ctsapxid01:50100/ProxyServer/register?ns=http://sap.com/xi/XI/Demo/Airline&interface=FlightSeatAvailabilityQuery_In&bean=FlightQueryIn&method=flightSeatAvailabilityQueryIn
    I followed the following blog
    http://wiki.sdn.sap.com/wiki/display/Java/JavaProxyChangesinPI7.1fromPI7.0
    Thanks,
    Chris

  • Java SE Runtime Environment 5.0u22 will not install on Windows 98SE

    Hi,
    I know, its no longer supported.
    As I understand, Java SE Runtime Environment 5.0u22 is the last SE Runtime that works with Windows 98SE and, if so, I need to install on a Windows 98SE computer.
    This Windows 98SE machine currently has Java 2 Runtime Environment, Standard Edition 5.0 for Windows installed on it.
    Downloaded jre-1_5_0_22-windows-i586-p.exe (offline installer version) from Sun, and when I click on this file it invokes my 56K dialer - once online, nothing happens, no HDD activity, no modem lights, nothing - and I do not get any error messages.
    If I choose to cancel the dialer, again, nothing happens, no HDD activity, no modem lights, nothing - and I do not get any error messages.
    I checked my MSI.DLL file and it is version 2.0.2600.2 - which is consistent with the installation requirements detailed here . . . http://www.oracle.com/technetwork/java/javase/install-windows-139179.html#installer2.0
    I ran a few Googles, but did not find any help.
    A few words of encouragement and suggestions of how to accomplish this install are sincerely appreciated.
    Many thanks,
    CurlySue

    Well, its been 10 days and no replies.
    Bummer.
    Guess there are no longer any JSE 5.0 experts online.
    Pity.
    CS

  • Error Message 1316 while uninstalling Java 2 Runtime Env SE v1.4.2_03msi

    I recently updated to Java 10 while in the process of clearing some nasty virus/malware off my system. I worked with a tech guide to do the clean up. He told me to uninstall old updates, including Java 2 Runtime Environment, SE v1.4.2_03. In the process, I got this error message:
    Error 1316 - A network error occurred while attempting to read from file C:\WINDOWS\Installer\Java 2 Runtime Environment, SE v1.4.2_03msi.
    then I clicked OK to continue and got a Fatal Error at the end and the uninstall was unsuccessful.
    The tech guide told me that "hackers can use script to infect you via these old versions." The virus/malware we caught was spyware and serious. I'm serious about getting clean... any advice please?
    Thanks -
    BirdieKaie

    Update 10. As in "C:\Program Files\Java\jre1.5.0_09\ <<< Java just updated to 10, update your version please."

  • Removing Java 2 Runtime Environment, SE v1.4.2_04

    I'm having problems removing this from my pc. I tried using the Add/Remove Programs and get an error message. Basically it ells me that "The file 'C:\Documents and Settings\Administrator\Local Settings\Application Data\etc.......... is not a valid installation package for the product Java 2 Runtime Environment SE v1.4.2_04 etc.......... etc........
    However when I do a browse to that location I do see the .msi package it is looking for. I tried to reinstall the package but cannot because it tells me I already have a version installed. How can I remove this? I'm willing to go as far as doing it manually. Thanks.
    Allen

    The security enhancements are documented at http://java.sun.com/j2se/1.5.0/ReleaseNotes.html#150_06
    Changes in 1.5.0_06
    Prior to this update [1.5.0_06], an applet or [Java Web Start] application could specify the version of the JRE on which it would run. This has changed. All applets are executed with the latest JRE version. Unsigned Java Web Start applications that specify a version other than the latest trigger a warning, requiring explicit user permission before the application will run. Signed Java Web start applications are not affected.
    In other words, only Applets and unsigned Java Web Start applications are affected by the security enhancements. Standalone applications can select any JRE they want, even if it is the outdated 1.4.2_13.

  • Java 2 runtime Environment setup failed with a return code of -1

    Hi!
    I have tried to install sdk 1_3_1_01 on Windows 2000 with ServicePack 2 and the error "Java 2 runtime Environment setup failed with a return code of -1" occured. As I saw, a lot of people has the problem but couldn't find a solution on this page!
    Please help !
    Me

    I've installed 1.3.1_01 on both W2K Workstation and Server, no problem. There's a bug report, but no workaround or solution.
    http://developer.java.sun.com/developer/bugParade/bugs/4412291.html
    and it's supposedly 'fixed' in 1.4.0 beta.
    http://java.sun.com/j2se/1.4/fixedbugs/fixedbugs-beta2.html
    You might try installing the beta version
    http://java.sun.com/j2se/

  • Eclipse give following error :could not find Java 2 runtime environment

    When I try to start eclipse it is giving me following error could not find Java 2 runtime environment.It was working fine untill I installed a new verson of eclipse although I am not whethar that is the source of problem.
    When i give java -version command in command prompt it shows
    Registry key 'Software\JavaSoft\Java Runtime Environment\CurrentVersion'
    has value '1.4', but '1.6' is required.
    Error: could not find java.dll
    Error: could not find Java 2 Runtime Environment.
    My java Home ,classpath , and path are all set as I say it was earliar woking fine.
    Please Help.

    I know this is a relatively old post, but some people can stumble on this page when doing a search for this problem.
    Anyway, I ran into this on my PC after I installed Sybase which had an older jre.
    Solution:
    1. Run regedit
    2. Look for Java Runtime Environment
    You may have to do multiple searches. Eventually you'll find one with the version number.
    3. Modify the value and change it to the correct version number. (in your case, you would have changed it from 1.4 to 1.6).
    This is much quicker than reinstalling Java every time installing something that uses an older version of Java hoses up the registry value.

Maybe you are looking for