How to load a .class file dynamically?

Hello World ;)
Does anyone know, how I can create an object of a class, that was compiled during the runtime?
The facts:
- The user puts a grammar in. Saved to file. ANTLR generates Scanner and Parser (Java Code .java)
- I compile these file, so XYScanner.class and XYParser.class are available.
- Now I want to create an object of XYScanner (the classnames are not fixed, but I know the filename). I tried to call the constructor of XYScanner (using reflection) but nothing works and now I am really despaired!
Isn't there any way to instantiate the class in a way like
Class c = Class.forName("/home/mark/XYScanner");
c scan = new c("input.txt");
The normal call would be:
XYLexer lex = new XYLexer(new ANTLRFileStream("input.txt"));The problem using reflection is now that the parameter is a ANTLRFileStream, not only an Integer, as in this example shown:
Class cls = Class.forName("method2");
Class partypes[] = new Class[2];
partypes[0] = Integer.TYPE;
partypes[1] = Integer.TYPE;
Method meth = cls.getMethod("add", partypes);
method2 methobj = new method2();
Object arglist[] = new Object[2];
arglist[0] = new Integer(37);
arglist[1] = new Integer(47);
Object retobj = meth.invoke(methobj, arglist);
Integer retval = (Integer)retobj;
System.out.println(retval.intValue());Has anyone an idea? Thanks for each comment in advance!!!

Dump all of your class files into a directory.
Use the File class to list all files and iterateover
the files.NastyNot really, when you are dynamically creating code, I would expect the output to be centralized, not spread out all over the place.
>
Use a URLClassloader to load the URL that isobtained
for each file with file.toURI().toURL()(file.toURL()
is depricated in 1.6)Wrong, the URL you give it must be that of the
directory, not the class file.No, I did this quite recently, you can give it a specific class file to load.
>
Load all of the classes in this directory, thatway
any anonymous classes are loaded as well.Anonymous classes automatically loaded when the real
one isIt can't load it if it doesn't know where the code is. Since you haven't used a URL classloader to load once class file at a time, you would never encounter this. But if you loaded a class file that had an anonymous classfile it needed, would it know where to look for it?
>
From this point you should be able to just get a
class with Class.forName(name)No. Class.forName uses the classloader of the class
it's called in, which will be the system classloader.
It won't find classes loaded by a URLClassLoader.got me there.

Similar Messages

  • How to Load a class file base on .class file name???

    Hi,
    Can anyone help me?
    1) Based on filename (d:\temp\bla.class), I want to load this bla.class and get the actual package of this class.
    example:
    package something.temp;
    public class bla
    I want to load the file base on filename and get the package of the class. Is it possible ?
    Thank you.

    Hi nikki96,
    It will not work. I will get java.lang.NoClassDefFoundError eventhough I extends classloader to use the findClass(String filename);
    Example:
    import java.security.*;
    import java.util.Enumeration;
    import java.util.NoSuchElementException;
    import java.util.jar.Attributes;
    import java.util.jar.Manifest;
    import sun.misc.Resource;
    import sun.misc.URLClassPath;
    public class MyURLClassLoader extends ClassLoader
    String host;
    int port;
    public Class findClass(String name)
                   try
         byte[] b = loadClassData(name);
         return defineClass(name, b, 0, b.length);
                   } catch(Exception e)
                        e.printStackTrace();
                   return null;
    private byte[] loadClassData(String name) throws Exception
                   // load the class data from the connection
                   File file = new File(name);
                   InputStream is = new FileInputStream(file);
                   long length = file.length();
                   // You cannot create an array using a long type.
                   // It needs to be an int type.
                   // Before converting to an int type, check
                   // to ensure that file is not larger than Integer.MAX_VALUE.
                   if (length > Integer.MAX_VALUE) {
                        // File is too large
                   // Create the byte array to hold the data
                   byte[] bytes = new byte[(int)length];
                   // Read in the bytes
                   int offset = 0;
                   int numRead = 0;
                   while (offset < bytes.length
                        && (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0) {
                        offset += numRead;
                   // Ensure all the bytes have been read in
                   if (offset < bytes.length) {
                        throw new IOException("Could not completely read file "+file.getName());
                   // Close the input stream and return bytes
                   is.close();
                   return bytes;
    Problem: The class file is not in the proper package (d:\temp\bla.class) where the proper package is d:\something\temp\bla.class.
    Objective: I just want to base on the bla.class (no matter where is it located), then get the package of the classfile (bla.class) like example something.temp.
    Simple as that but I don't know how to do :(.

  • How to load Java properties file dynamically using weblogic server

    Hi,
    We are using Java properties file in Java code. Properties in java properties file are frequently modified. If I keep these properties file in project classpath or as part of war, I will have to redeploy application after each change.
    We are using Weblogic Server.
    Can you please suggest me how can this properties file be loaded at weblogic server startup. Then in that case, how to refer property file in Java code?
    What is the best practice for this?
    Thanks,
    Parshant

    Another alternative is, keep the property file in any pre-defined location. Write a class which reads the properties from the file and returns the one which is requested by caller and deploy this class. Whenever you have to change the properties just update the property file on server and next call to fetch the property should return the updated one.
    Downside of this approach is file I/O everytime. To overcome that you can actually "cache" the properties in a hashmap. Basically when any property if requested, first check the hashmap, if not found then only read from property file and also update in hash map. Next time same property will be returned from hash map itself. The hash map will be cleared at every server restart since its in the memory. You will also need to build a method to clear the hashmap when you update the values in the property file on server.
    This solution would be suitable for small size files and when network overhead of calling a DB needs to be avoided.

  • How to load a Jar file in the class path?

    How to load a Jar file which contains class files, images, etc.. in the classpath without using URLClassLoader.

    You don't "load" jars. If it's on the classpath, you can obtain individual resources from it using various methods on either Class or ClassLoader. Do you mean "how to add a jar to the classpath at runtime"? Can't be done without using a classloader, typically URLClassLoader or a subclass thereof. Why you want to not use the proven method is beyond me. Presumably because you don't understand classloading. In which case, forget it.

  • How to load a client file in a clob using sqlcl

    How to load a client file in a clob using sqlcl

    You don't "load" jars. If it's on the classpath, you can obtain individual resources from it using various methods on either Class or ClassLoader. Do you mean "how to add a jar to the classpath at runtime"? Can't be done without using a classloader, typically URLClassLoader or a subclass thereof. Why you want to not use the proven method is beyond me. Presumably because you don't understand classloading. In which case, forget it.

  • How to load java class from jsp page?

    hi all!
    Does anyone know how to load java class from jsp page?
    I try to load java class from jsp page.
    Is it possible to load java class fom jsp page?
    thanks and have a good day!

    What I mean is How to load/open java class file from jsp page?
    I think we can open Applet from jsp page by using
    <applet code=helloApplet.class width=100 height=100>
    </applet>
    but, how to open java class which is an application made by Frame?
    thanks and have a good day

  • Stuck - load the Excel file dynamically with different columns and worksheet names

     I have a situation where I want to load the Excel file dynamically, and the excel file have different columns or even worksheet name. Any idea how I could
    approach this? I believe there's no way to modify the meta data (specifically the mapping) in the data flow.

    Hi Chimumu,
    The SSIS stock adapters don't supporting dynamic column mapping, to achieve your goal, you need to use Script Task/Component to read the Excel sheet name and the columns in the worksheet, and then map to the output columns of the script component. You can
    also refer to the following blogs:
    http://micktechblog.blogspot.com/2011/06/ssis-excel-import-with-unknown-number.html
    http://wikiprogrammer.wordpress.com/2011/04/08/dynamic-column-mapping-in-ssis-part-1/
    Regards,
    Mike Yin
    TechNet Community Support

  • How to clear old class files cached in JVM

    JVM stores old class files in its cache even after the corresponding files have been deleted from the database. This causes a conflict if a new file is saved with the same name as one that was deleted earlier causing old data to be fetched and not the new one.
    am using the following line of code to load the class file :
    Class.forName(className, false, this.getClass().getClassLoader())
    please help
    Thanks - N

    Why are you trying to do that?
    Dynamic Classloading(reloading) has a meaing only on "application container" like WAS.
    Not appropriate for normal applcation.
    Focus on enhancing your application logic and algorithm rather than wasting your brain on difficult and meaningless things. Applying some flexible design patterns wouldn't suffice?
    Anyway, Sun provides wonderful and simple custom classloader sample.
    http://java.sun.com/developer/onlineTraining/Security/Fundamentals/magercises/ClassLoader/help.html
    Anayzing tomcat source(which is downloadable) is another approach.
    Edited by: Dion_Cho on Nov 26, 2007 5:18 PM
    Typo...

  • How i load java class through javascript

    Hi,
    i want to load java class file at client side through the java script. Class file wich already at client side(client machine)
    tell me is it possible....
    thanks
    plzz mail
    [email protected]

    From your post it is not very clear what you want to do.
    1. Even if it was possible to load client classes using javascript, how on earth are you going to execute them ??? JavaScript and java are entirely different cups of tea.
    2. If it was an applet, then probably you can access some classes from the client machine. Definely the default packages. However, I don't know whether you can access other classes. That might lead to a security issue. Please check with a java securities expart.
    3. Loading a class from the client machine is DEFINITELY A BAD PROGRAMMING PRACTICE Use the codebase property on your applet tag to load the classes from the server.

  • How to convert java class file version without decompiling

    Hi,
    Oracle R12.1.3 i am having illegal access error while try to access the class file version Java 1.3 uses major version 47,So how to convert the class file version without using decompiling.
    Current java version is 1.6.0_07
    Is there any tool or API for converting class file version?
    Thanks,
    Selvapandian T

    Beside this I wonder where you get your error from since AFAIK 12c comes with java 1.6.
    Well wonder no more!
    OP isn't using Oracle 12c database.
    They are using Oracle R12.1.3 - which is the E- Business Suite.

  • How to convert a class file to exe file and how to cteate a class file to d

    how to convert a class file to exe file

    Hi Bhaskarq,
    Hi,
    It is not at all possible.
    But it is a really worst method.
    Please go through it.
    This is a very common question asked in the comp.lang.java newsgroup. Its often useful to have an
    executable application when deploying your
    applications to a specific platform, but remember to
    make your .class files available for users running
    Unix/Macintosh/other platforms.
    Microsoft provide a free system development kit (SDK),
    for Java, which includes the jexegen tool. This
    will convert class files into a .EXE form. The only
    disadvantage is that users need a Microsoft Java
    Virtual Machine (JVM) installed. If your target
    platform is Win32, you can either redistribute the
    virtual
    machine, or raise the level of your system
    requirements, to include Windows 98, or Windows 95
    with
    Internet Explorer 4. Systems matching these
    requirements will already have a copy of the Microsoft
    Java Virtual Machine installed.
    Note : You must specify all of the class files your
    application needs (except for standard java packges)
    as a parameter, so if you have third party libraries,
    you'll need to include them as well. You can use wildcards * though, and you don't need the original source code.
    Also please see this Forum which will give a good idea
    http://forum.java.sun.com/thread.jsp?forum=31&thread=149733
    I hope this will help you.
    Thanks
    Bakrudeen
    Technical Support Engineer
    Sun MicroSystems Inc, India

  • How to Load a class manually

    Hello Friends,
    I need a help regarding how to load a class manually.
    i have the class name -- TestClass1
    and Path - com.apps.classes
    Thank you

    Thank You------
    I got the result
    String classPath = com.apps.className;
    Object obj = Class.forName(classPath).newInstance();

  • How to load an XML file to oracle9i server?

    I want to use XSU DBMS_XMLsave package to load an XML file to a relational table using PL/SQL from a distant server. Now, I don't know how to load that XML file to the distant server.
    Somebody help me?

    I want to use XSU DBMS_XMLsave package to load an XML file to a relational table using PL/SQL from a distant server. Now, I don't know how to load that XML file to the distant server.
    Somebody help me?

  • "how to load a text file to oracle table"

    hi to all
    can anybody help me "how to load a text file to oracle table", this is first time i am doing, plz give me steps.
    Regards
    MKhaleel

    Usage: SQLLOAD keyword=value [,keyword=value,...]
    Valid Keywords:
    userid -- ORACLE username/password
    control -- Control file name
    log -- Log file name
    bad -- Bad file name
    data -- Data file name
    discard -- Discard file name
    discardmax -- Number of discards to allow (Default all)
    skip -- Number of logical records to skip (Default 0)
    load -- Number of logical records to load (Default all)
    errors -- Number of errors to allow (Default 50)
    rows -- Number of rows in conventional path bind array or between direct path data saves (Default: Conventional path 64, Direct path all)
    bindsize -- Size of conventional path bind array in bytes (Default 256000)
    silent -- Suppress messages during run (header, feedback, errors, discards, partitions)
    direct -- use direct path (Default FALSE)
    parfile -- parameter file: name of file that contains parameter specifications
    parallel -- do parallel load (Default FALSE)
    file -- File to allocate extents from
    skip_unusable_indexes -- disallow/allow unusable indexes or index partitions (Default FALSE)
    skip_index_maintenance -- do not maintain indexes, mark affected indexes as unusable (Default FALSE)
    commit_discontinued -- commit loaded rows when load is discontinued (Default FALSE)
    readsize -- Size of Read buffer (Default 1048576)
    external_table -- use external table for load; NOT_USED, GENERATE_ONLY, EXECUTE
    (Default NOT_USED)
    columnarrayrows -- Number of rows for direct path column array (Default 5000)
    streamsize -- Size of direct path stream buffer in bytes (Default 256000)
    multithreading -- use multithreading in direct path
    resumable -- enable or disable resumable for current session (Default FALSE)
    resumable_name -- text string to help identify resumable statement
    resumable_timeout -- wait time (in seconds) for RESUMABLE (Default 7200)
    PLEASE NOTE: Command-line parameters may be specified either by position or by keywords. An example of the former case is 'sqlldr scott/tiger foo'; an example of the latter is 'sqlldr control=foo userid=scott/tiger'. One may specify parameters by position before but not after parameters specified by keywords. For example, 'sqlldr scott/tiger control=foo logfile=log' is allowed, but 'sqlldr scott/tiger control=foo log' is not, even though the position of the parameter 'log' is correct.
    SQLLDR USERID=GROWSTAR/[email protected] CONTROL=D:\PFS2004.CTL LOG=D:\PFS2004.LOG BAD=D:\PFS2004.BAD DATA=D:\PFS2004.CSV
    SQLLDR USERID=GROWSTAR/[email protected] CONTROL=D:\CLAB2004.CTL LOG=D:\CLAB2004.LOG BAD=D:\CLAB2004.BAD DATA=D:\CLAB2004.CSV
    SQLLDR USERID=GROWSTAR/[email protected] CONTROL=D:\GROW\DEACTIVATESTAFF\DEACTIVATESTAFF.CTL LOG=D:\GROW\DEACTIVATESTAFF\DEACTIVATESTAFF.LOG BAD=D:\GROW\DEACTIVATESTAFF\DEACTIVATESTAFF.BAD DATA=D:\GROW\DEACTIVATESTAFF\DEACTIVATESTAFF.CSV

  • How to get the .class file for the extended Controller .java file

    Hi,
    I did the below steps.
    1. Created New OAWorkspace
    2. Created New project
    3. Imported the page .xml file
    4. Added new .java file by extending the controller class
    5. Added code in the .java file.
    6. Ran the .xml file
    As I copied all the folders from Unix box, the page was opened.
    But My question was where can I see the .class file the extended controller. It's a .java file. How to compile and get the .class file for this .java file. If I get this .class file, I can go to the page and click the personlize page. and change the Controller name to the new path by ftp ing the new class to the cust.oracle.apps.pos.changeorder.webiui.
    Please let me know how to create the .class file.
    Thanks,
    HP

    All are Java files are stored in JDEV_INSTALL_DIR:\jdevhome\jdev\myprojects\
    In your case the path java would be
    JDEV_INSTALL_DIR:\jdevhome\jdev\ myprojects \cust\oracle\apps\pos\changeorder\webui\
    AND
    Once you compile the java file in Jdeveloper, Class files get generated @ below path
    In your case the path of class would be
    JDEV_INSTALL_DIR:\jdevhome\jdev\ myclasses \cust\oracle\apps\pos\changeorder\webui\
    Duplicate Thread-
    Thanks
    --Anil
    http://oracleanil.blogspot.com/

Maybe you are looking for

  • Unable to specify username password for emulator sessions on MAC OS 10.5.2

    We have a strange issue at one of our customers. When the want to start an emulator session the login dialog box does not accept keystrokes when started from a MAC-client with MAC OS 10.5.2 (X11 version 2.1.1). People cannot enter their credentials a

  • Any Maxl Script to Export and import of Partition

    Hi All, Is there any maxl or Esscmd command which will do an Export or an import of the partition. Regards, Krishna.

  • Motion tweens from keyframe vs properties panel

    When motion tweening a grouped object in either Flash 8 or Flash CS3, I get different results depending on whether I use the keyframe or the properties panel to set the tween. If I right-click the first keyframe and select "Create Motion Tween," I ge

  • ERROR: cannot edit or duplicate page. Reason: no editable regions

    Hi, Going round in circles with this one.  Feeling like Friday afternoon. URL: http://www.business-risc.com/fleet/bss/1/index.html CtrlE works fine. Click on "POLICIES" spry tab Click on EDIT PAGE Highlights the correct editable region... hover confi

  • Generate a single pulse - long width ( 160sec)

    Hello, I have a DAQ Pad6052E. I want to generate a single pulse with one of the 2 counter/timer. It works for pulse width (high state) below ~160secondes. For my application I need to generate a much longer pulse width.  I want to have a pulse width