Loading a jar via a custom classloader

Hi,
I have written a custom class loader that allows me to load a compiled java program as a collection of class files at runtime.
This is nice however I now need to consider the runtime execution of more complex java programs that have custom library dependencies.
This means loading a .jar library into the classloader. I can get the contents of a jar and load specific classes by name via reflection but I want to load the entire jar into the classloader so that its contents can be used 'as needed' much like a jar on the system classpath.
Is this possible? If so I would like to know how as I have been struggling with this problem and cannot see a solution.
Regards,
Stephen

However I still don't understand why you need to
actually load all those classes initially. Afterall,
URLClassLoader (which sounds a lot like what youare
describing) only loads classes as needed.i have just built a swing app that accesses an oracle
database, i jared together all the classes, and i did
something in the manfest file so that you can just
double clisk the jar and it fires up like an exe.
doing it this way everything is fine except it cannot
access the database, the reason is those oracle
classes are not loaded, even they are on the path - i
can run the app using a batch file but i dont like it
as it opens up a dos window. this is an example, as i
was told, where it is necessary to load all thoses
oracle database classes initially. Dear, daFei.
I believe that you are getting confused between the way the system will ignore that CLASPPATH environment variable when you run a java application packaged as a jar file with the -jar switch (the classpath for the jar can be set in the manifest) and what I am attempting to-do which is to run a compiled java program at runtime and dynamically load any dependant libraries.
Stephen

Similar Messages

  • Customer ClassLoader:  keeping JWS from loading jars

    I really like the ability of JWS to be able to download jars required for my application to run, but there are several jars that I need the ability to load up via a custom ClassLoader. But because JWS includes all of these jars in the classpath upon application start, the system class loader will take the first class it can find. Because I need to load classes from these jars based upon something a user selects, I need to have control over the codesource for these classes. Does anyone have any ideas on how to tackle this problem? Not include the jars in the jnlp and then download if not cached locally, if that's the case what's the best way to do that? Include in jnlp and be able to load with custom classloader(I dont think this will work)? Any ideas on this would greatly be appreciated.

    Easiest solution to your problem and still being able to use the update mechanism of JWS is to include your JAR-file in another JAR-file that JWS loads, and then write up your own classloader, which tries to fetch your JAR-file from the downloaded JAR-file (if JWS already downloaded it, otherwise JWS will download it).
    The contents of the jws-stub.jar would be something
    of the following ;).
    jws-stub.jar
    --> myjar1.jar
    --> myjar2.jar
    org.myjar.MyJarClassloader
    Then based on your user selecting something you
    can decide which JAR-file you want to load, and thus
    which class.
    Hope this helped,
    Manfred.

  • CLASSPATH issues on DOS/NT and loading of jar files

    Hello all,
    I have the following problem on running WebLogic 5.1 on
    NT. The CLASSPATH is getting truncated after a certain number of
    characters. I have a lot of third party jar files that I use in my
    application. How do I overcome this problem ? I tried increasing my DOS
    environment space by changing the default values in config.sys.
    What are other alternatives ?
    One idea that I have is to use URLClassLoader to load the jar files. I
    am running a RMI based application and I need to load these jar files
    before I load the RMI code. Where would I run this URLClassLoader code
    ? Is there some system startup class that can load jar files ?
    Thanks,
    Aswin.

    Thanks for the reply. I much appreciate it. What about the other idea that I
    had outlined-loading these jar files using a ClassLoader. Is that viable ?
    Aswin.
    Cameron Purdy wrote:
    In Win2k: Control Panel, System, Advanced, Environment Variables
    ComSpec=%SystemRoot%\system32\cmd.exe /e:16384
    You still will not be able to have a command line exceeding a certain size
    (around 1k or so). That is a hardcoded limit somewhere inside the NT kernel
    ("kernel" being a poor term for the piece so named in NT ;-).
    Peace,
    Cameron Purdy
    Tangosol, Inc.
    http://www.tangosol.com
    Tangosol: How Weblogic applications are customized
    "Aswin Dinakar" <[email protected]> wrote in message
    news:[email protected]..
    Hello all,
    I have the following problem on running WebLogic 5.1 on
    NT. The CLASSPATH is getting truncated after a certain number of
    characters. I have a lot of third party jar files that I use in my
    application. How do I overcome this problem ? I tried increasing my DOS
    environment space by changing the default values in config.sys.
    What are other alternatives ?
    One idea that I have is to use URLClassLoader to load the jar files. I
    am running a RMI based application and I need to load these jar files
    before I load the RMI code. Where would I run this URLClassLoader code
    ? Is there some system startup class that can load jar files ?
    Thanks,
    Aswin.

  • Error Loading xmlparserv2.jar

    Platform: NT4 SP5
    Database: 8.1.6
    When loading xmlparserv2.jar via loadjava, I'm getting an ORA-01401: inserted value too large for column.
    Command:
    loadjava -user eclipse/eclipse@bugs -r -v xmlparserv2.jar
    Errors:
    loading : oracle/xml/parser/v2/mesg/XMLErrorMesg_zh_CN.properties
    creating : oracle/xml/parser/v2/mesg/XMLErrorMesg_zh_CN.properties
    Error while creating resource oracle/xml/parser/v2/mesg/XMLErrorMesg_zh_CN.prope
    rties
    ORA-00604: error occurred at recursive SQL level 1
    ORA-01401: inserted value too large for column
    ORA-06512: at line 2
    loading : oracle/xml/parser/v2/mesg/XMLErrorMesg_cs_CZ.properties
    creating : oracle/xml/parser/v2/mesg/XMLErrorMesg_cs_CZ.properties
    Error while creating resource oracle/xml/parser/v2/mesg/XMLErrorMesg_cs_CZ.prope
    rties
    ORA-00604: error occurred at recursive SQL level 1
    ORA-01401: inserted value too large for column
    ORA-06512: at line 2
    I just manually upgraded to 8.1.6 from an 8.1.5 database. I also ran jvmu815.sql to upgrade the JVM.
    I noticed that there is a patch out for 8.1.6, would this be helpful to install?
    Thanks.
    null

    Christine,
    I apologize for the delay.
    I verified that the system is OK so I believe that the solution is a good work around.
    1.) Export the schema that you want to utilize the XML Parser and all the schema constraints, procedures, etc.
    2.) Drop the user/schema and cascade all of the user's objects.
    3.) Recreate the user with the same priveledges and with the same default and temp storage locations.
    4.) Load the xmlparserv2.jar and the xmlplsql.jar files with loadjava as the user you just recreated.
    5.) Run the sql script to create the java packages as the same user.
    6.) Now, import the schema that you exported in step 1.
    7.) After the import, I had to recompile three xml package bodies. They were: XMLDOM, XMLPARSER and XMLPROCESSOR. Check them to see if they are invalid in your user's shema.
    Good luck,
    Eric

  • Loading an entire JAR via a classloader

    Hi how would I load an entire JAR file via a classloader. Currently I'm able to load one file at a time (in this case org.w3c.dom.Node) as shown below:
    import java.net.*;
    public class MyJarLoader {
       public static void main(String [] args) throws Exception {
         URL[] urlsToLoadFrom = new URL[]{new URL("file:subdir3/xml-apis.jar")};
         URLClassLoader loader1 = new URLClassLoader(urlsToLoadFrom);
         Class cls1 = Class.forName("org.w3c.dom.Node", true, loader1);
         System.out.println("Loaded '"+cls1.getName()+"'");
         org.w3c.dom.Node Node = (org.w3c.dom.Node) cls1.newInstance();
    Thanks

    Figured this one out as below. Note this is the simplistic solution since it requires that the jar files be present in the classpath. If not, you will have to write your own loadClass method to read the data from the zip (& then can't use the method 'Class.forName()').
    Regards
    //Load Apache JAR files
    URL[] urlArrToLoadFrom = new URL[]{new URL("file:xalan-j_2_5_0/xml-apis.jar"),
                new URL("file:xalan-j_2_5_0/xercesImpl.jar"), new URL("file:xalan-j_2_5_0/xalan.jar")};
    //Create a URLClassLoader to access jar files
    URLClassLoader urlLoaderGeneric = new URLClassLoader(urlArrToLoadFrom);
    //Foreach jar file, open, load class files & close
    for(int i=0; i<urlArrToLoadFrom.length; i++) {
    //Debug
       System.out.println(urlArrToLoadFrom.toString());
       //Open zip file
       ZipFile zf = new ZipFile(urlArrToLoadFrom[i].getFile());
       for (Enumeration enum = zf.entries(); enum.hasMoreElements();) {
         //Get entry
         ZipEntry ze = (ZipEntry) enum.nextElement();
         //Only load if it's not a directory and it's a class file
         int iIndexClass = -1;
         if (!ze.isDirectory() && ((iIndexClass = ze.getName().indexOf(".class")) != -1)) {
             //Remove .class & replace / with .
             String strApacheClassName = (ze.getName().substring(0,iIndexClass)).replace('/','.');
             //Load class file
             Class classApache = Class.forName(strApacheClassName, true, urlLoaderGeneric);
             System.out.println("Loaded '"+classApache.getName()+"'");
       //Close zip
       zf.close();

  • Loading jar at runtime using custom classloader

    Hi,
    I'm trying to load a jar file to an application running inside weblogic at runtime.
    I followed the example that was posted at
    http://dev2dev.bea.com/cs/user/blog?file=/blog/jcscoobyrs/archive/2005/05/realworld_use_f.html
    and did the following:
    URLClassLoader loader = null;
    URL[] urls = {new URL("file:///" + "C:/Program Files/aaa/WEB-INF/lib/ImportTest3.jar")};
    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    ClassLoader loader = new URLClassLoader(urls, classLoader);
    Thread.currentThread().setContextClassLoader(loader);
    Class customClass = Class.forName(className, true, loader);
    customCode = customClass.newInstance();
    Thread.currentThread().setContextClassLoader(classLoader);
    everything works fine when I access my application once.
    But when I'm trying to do the same again, everything fails.
    Any ideas?
    Thanks!

    When you say everything fails - can you clarify the failure? Can you paste the stacktrace? Is it a ClassNotFoundException?

  • Jar files not in WEB-INF/lib (custom ClassLoader?)

    I need to use classes in my JSP that do not come from a JAR file in the standard location. Sounds like I "simply" need to extend the ClassLoader used by the app server for loading the JSP. Is there any way of doing that?
    Example: my.jsp
    <h1>Hi</h1>
    <%
    FOO x = new FOO(); // code from a non-standard place
    ClassLoader cl = getClass().getClassLoader();
    %>
    I cannot put FOO.class into WEB-INF/lib or any of the standard places. Ideally I'd like to give the ClassLoader (cl above) a different (custom) parent ClassLoader which would know how to resolve FOO.class.
    I've poured over docs and Google and WebSphere and the Tomcat source code. Is this request of mine really so outrageous? I'm about the give up. What good are custom classloaders if one can't use them?

    You are essentially making the argument "All that Java
    needs is a URLClassLoader, and no one has any need for
    any custom ClassLoaders". (After all, that's all that
    I seem to have in a JSP context, with a list of
    hard-coded URLs into that URLClassLoader ...)
    Do a Google search on "custom ClassLoader" and you
    will find lots of reasons why people want to have
    custom ClassLoaders, such as ones that don't use any
    JAR or .class files ... which would qualify as why I
    can't put them into a certain place ...To be fair to duffymo, that is not how I read his argument. I read it as:
    "Sometimes we try to do things the hard way. If we sit back and rethink the problem, an easier solution might come about."
    I think this is a good opportunity to explain why you can not use the normal class loader heirarchy. You have no JARs and no .class files? Then where are you getting the class definitions? If you explain enough so that we might understand the problem:
    1) we might be able to come up with a solution or
    2) you might see a different approach before you are even done explaining
    #2 has happened to me more times then I can count. I sit down formulating a question for the forums, make sure I include enough detail to explain my problem. And by the time I am done I have a new (usually simpler) approach to solving the problem.
    Or you could sit and defend your first approach without providing any context and accomplish nothing. So its up to you.

  • How to load an applet using custom classloader ?

    Hi All,
    How to load an applet using custom classloader rather than using default browsers classloader i.e AppletClassLoader usually ?
    Regards,
    Kumar.

    I would guess that that would require two applets.
    The first does nothing but create the custom class loader and then load the second applet.

  • Loading EAR or WAR using a Custom Classloader

    Hi, everybody.
    First of all I'm aware of http://download.oracle.com/docs/cd/E12840_01/wls/docs103/programming/classloading.html
    Is is possible to "insert" a custom classloader in this hierarchy? I need a custom classloader to load special resources for my webapp. This custom classloader can be added right after the system classloader, acting as the parent classloader of my app (ear or war) classloader. Is it doable? How?
    Thanks in advance.
    Best regards,
    Daniel.

    My workaround won't work. The app classloader is accessible but it isn't an URLClassLoader, so i am unable to change its classpath.
    <16/05/2011 18h01min11s BRT> <Notice> <WebLogicServer> <BEA-000365> <Server state changed to STANDBY>
    <16/05/2011 18h01min11s BRT> <Notice> <WebLogicServer> <BEA-000365> <Server state changed to STARTING>
    preStart
    thread cl = weblogic.utils.classloaders.GenericClassLoader@1d5176d finder: weblogic.utils.classloaders.CodeGenClassFinder@330301 annotation: app@
    this cl = weblogic.utils.classloaders.GenericClassLoader@1d5176d finder: weblogic.utils.classloaders.CodeGenClassFinder@330301 annotation: app@
    thread cl instanceof URLClassLoader = false
    this cl instanceof URLClassLoader = false
    === Starting app ===
    sysCl = sun.misc.Launcher$AppClassLoader@13f5d07
    threadCl = weblogic.utils.classloaders.ChangeAwareClassLoader@17df9ec finder: weblogic.utils.classloaders.CodeGenClassFinder@af0e38 annotation: app@test_war
    sysCl = weblogic.utils.classloaders.ChangeAwareClassLoader@17df9ec finder: weblogic.utils.classloaders.CodeGenClassFinder@af0e38 annotation: app@test_war -> weblogic.utils.classloaders.GenericClassLoader@1d5176d finder: weblogic.utils.classloaders.CodeGenClassFinder@330301 annotation: app@ -> weblogic.utils.classloaders.FilteringClassLoader@2096d7 finder: weblogic.utils.classloaders.CodeGenClassFinder@18f12dc annotation: -> weblogic.utils.classloaders.GenericClassLoader@fbf51d finder: weblogic.utils.classloaders.CodeGenClassFinder@1f4b24 annotation: -> sun.misc.Launcher$AppClassLoader@13f5d07 -> sun.misc.Launcher$ExtClassLoader@f4a24a
    threadCl = weblogic.utils.classloaders.ChangeAwareClassLoader@17df9ec finder: weblogic.utils.classloaders.CodeGenClassFinder@af0e38 annotation: app@test_war ->weblogic.utils.classloaders.GenericClassLoader@1d5176d finder: weblogic.utils.classloaders.CodeGenClassFinder@330301 annotation: app@ -> weblogic.utils.classloaders.FilteringClassLoader@2096d7 finder: weblogic.utils.classloaders.CodeGenClassFinder@18f12dc annotation: -> weblogic.utils.classloaders.GenericClassLoader@fbf51d finder: weblogic.utils.classloaders.CodeGenClassFinder@1f4b24 annotation: -> sun.misc.Launcher$AppClassLoader@13f5d07 -> sun.misc.Launcher$ExtClassLoader@f4a24a
    postStart
    thread cl = weblogic.utils.classloaders.GenericClassLoader@1d5176d finder: weblogic.utils.classloaders.CodeGenClassFinder@330301 annotation: app@
    this cl = weblogic.utils.classloaders.GenericClassLoader@1d5176d finder: weblogic.utils.classloaders.CodeGenClassFinder@330301 annotation: app@
    thread cl instanceof URLClassLoader = false
    this cl instanceof URLClassLoader = false
    <16/05/2011 18h01min46s BRT> <Notice> <Log Management> <BEA-170027> <The Serverhas established connection with the Domain level Diagnostic Service successfully.>
    =====================================================================
    http://pastie.org/1912944
    package abc;
    import java.net.URLClassLoader;
    import weblogic.application.ApplicationException;
    import weblogic.application.ApplicationLifecycleListener;
    import weblogic.application.ApplicationLifecycleEvent;
    public class MyAppListener extends ApplicationLifecycleListener {
         @Override
         public void postStart(ApplicationLifecycleEvent evt)
                   throws ApplicationException {
              System.out.println("postStart");
              printClassLoaders();
         @Override
         public void preStart(ApplicationLifecycleEvent evt)
                   throws ApplicationException {
              System.out.println("preStart");
              printClassLoaders();
         protected void printClassLoaders() {
              ClassLoader[] cls = new ClassLoader[] {
                        Thread.currentThread().getContextClassLoader(),
                        getClass().getClassLoader() };
              System.out.println("thread cl = " + cls[0]);
              System.out.println("this cl = " + cls[1]);
              System.out.println("thread cl instanceof URLClassLoader = "
                        + (cls[0] instanceof URLClassLoader));
              System.out.println("this cl instanceof URLClassLoader = "
                        + (cls[1] instanceof URLClassLoader));
    }

  • Custom ClassLoader = frustration & pain.

    Short version : I need to override the findLibrary() method of ClassLoader so I can load .dlls from a .jar. I can't simply loadLibrary() or load() them because when one particular .dll is loaded (j3dcore-ogl-cg.dll) it insists on attempting to load its dependents. If I have control of findLibrary(), then I can load them from wherever I want.
    The problem is, I can't see my ClassLoader in use. Here's the skeleton of what I'm using as the ClassLoader :
    public class Test extends ClassLoader
         public static void main(String[] args)
              System.out.println("Test parent class loader = "+Test.class.getClassLoader());
              Test l = new Test(
                   Test.class.getClassLoader()
              System.out.println("Custom class loader = "+l);
              try
                   Class<?> test2 = l.loadClass("Test2", true);
                   Method main = test2.getMethod("main", Array.newInstance(String.class, 0).getClass());
                   main.invoke(null, new Object[] {args});
              catch (SecurityException e)          {     e.printStackTrace();     }
              catch (NegativeArraySizeException e)     {     e.printStackTrace();     }
              catch (IllegalArgumentException e)     {     e.printStackTrace();     }
              catch (ClassNotFoundException e)          {     e.printStackTrace();     }
              catch (NoSuchMethodException e)          {     e.printStackTrace();     }
              catch (IllegalAccessException e)          {     e.printStackTrace();     }
              catch (InvocationTargetException e)     {     e.printStackTrace();     }
         Test(ClassLoader parent)
              super(parent);
    }and here's the class I'm loading :
    public class Test2
         public static void main(String[] args)
              System.out.println("Daughter class loader = "+Test2.class.getClassLoader());
    }The parent of my ClassLoader is sun.misc.Launcher$AppClassLoader@11b86e7 which I guess is the system class loader.
    My custom loader identifies as Test@3e25a5However, the daughter class that's loaded identifies its class loader as sun.misc.Launcher$AppClassLoader@11b86e7Why is this? Why isn't my class loader being used to load the class? I'm developing in Eclipse - would that make a difference?
    Thanks for any pointers, and apologies for any stupid mistakes.

    jtahlborn wrote:
    yes, that is feasible. the problem with your test classloader is that classloaders load classes in "parent first" order (by default). therefore, since your Test2 class is available from the app classloader, that is where it is loaded from. in order to have it loaded from your classloader, you have to either make it not available via the parent classloader, or change the "parent first" delegation by overloading one of the appropriate methods in ClassLoader. however, this isn't really relevant to what you want to do, because you want to change findLibrary, not findClass.Aha. I'm completely new to custom class loaders, and this "parent first" delegation model was throwing me. I couldn't figure out a way of hiding the class I wanted to load, so I overrode loadClass(String, boolean). Does this look sensible to you (apart from the odd error I know I'm not catching) ?
    @Override protected synchronized Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException
              if (!name.equals("Test2"))
                   return super.loadClass(name, resolve);
              System.out.println("loadClass("+name+","+resolve+")");
              File classFile = new File("Test2.class");
              long length = classFile.length();
              byte[] buf = new byte[(int)length];
              FileInputStream fis = null;
              try
                   fis = new FileInputStream(classFile);
                   int offset = 0;
                   int numRead = 0;
                   while ((offset < buf.length) && (numRead = fis.read(buf, offset, buf.length-offset)) >= 0)
                       offset += numRead;
                   if (offset < buf.length)
                        throw new IOException("Could not completely read file " + classFile.getName());
                   fis.close();
              catch (FileNotFoundException e)
                   // TODO Auto-generated catch block
                   e.printStackTrace();
              catch (IOException e)
                   // TODO Auto-generated catch block
                   e.printStackTrace();
              finally
                   if (fis != null)
                        try
                             fis.close();
                        catch (IOException e)     {}
            return super.defineClass("Test2", buf, 0, (int)length);
         }It feels... odd, having to duplicate code like that instead of just using super() and using the result, but it does work.
    Anyway, this is partly just a test. I need to be the ClassLoader for the loaded class so that I can then override findLibrary().
    that said, are you sure that the subsequent attempts to load dlls from the first dll go through the java findLibrary method? i would imagine that dlls use os specific means to find the other dlls.No clue! However, given that the Exception (hmm... sometimes an Exception, sometimes a severe Error) looks like :
    Exception in thread "main" java.lang.UnsatisfiedLinkError: C:\Documents and Settings\[...]\Local Settings\Temp\IST_1277997889218\j3dcore-ogl-cg.dll: Can't find dependent libraries
            at java.lang.ClassLoader$NativeLibrary.load(Native Method)
            at java.lang.ClassLoader.loadLibrary0(Unknown Source)
            at java.lang.ClassLoader.loadLibrary(Unknown Source)
            at java.lang.Runtime.load0(Unknown Source)
            at java.lang.System.load(Unknown Source)
            at SystemTest.loadLib(SystemTest.java:144)
            at SystemTest.loadFromJar(SystemTest.java:110)
            at SystemTest.<clinit>(SystemTest.java:91)
            at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
            at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
            at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
            at java.lang.reflect.Method.invoke(Unknown Source)
            at SystemTestLauncher.main(SystemTestLauncher.java:42)This suggests to me that either Java is trying to load the dependent libraries itself, or that the OS is failing, reporting an error to the VM, which is then packaging it up for me as an exception. I'm hoping for the former.
    Once I'm the class loader, I should at least be able to tell what's happening.
    Thanks for the hints!
    Edited by: CodeMonkey9358 on Jul 1, 2010 8:30 AM

  • The struggle of creating a Custom ClassLoader for Native libraries

    Hello Everyone,
    I'm having a really hard time writing and using my own ClassLoader in a Java Applet.
    Context :
    As the this link shows - http://codethesis.com/tutorial.php?id=1 - loading and especially unloading native libraries through Java requires defining our own ClassLoader, and use it to instantiate a class loading a library. When the class using native libraries has finished execution, setting all references to the classloader and calling the garbage collector will cause the native library to be unloaded. The class to load within the custom classloader is thus read byte after byte from the jar and defined using the Classloader.defineClass(..) function. So that's what I did. But I've got two problems.
    Problem 1 :
    On one single machine over 15 tested, the magic number of a given class read from the Jar using Applet.class.getResourceAsStream(classname) takes a value different from CAFEBABE and the defineClass function then throws an "Incompatible magic value" exception (see below). The workaround I found is to force the first 4 bytes of the byte array read from the class with CAFEBABE. But I still would like to understand why it takes a different value on this machine.
    Exception in thread "thread applet-MyApplet.class-1" java.lang.ClassFormatError: Incompatible magic value 409165630 in class file Reader
    at java.lang.ClassLoader.defineClass1(Native Method)
    at java.lang.ClassLoader.defineClass(Unknown Source)
    at NativeClassLoader.findClass(Unknown Source)
    Problem 2 :
    On windows, the NativeClassLoader works perfectly, but on Linux, I'm getting a java.lang.VerifyError (see below).
    Code is compiled with java 1.6.0_06 on windows XP. I tried to remove everything related to native code (remove .so load), the same error is raised.
    java.lang.VerifyError: (class: Reader, method: <clinit> signature: ()V) Illegal instruction found at offset 1
    at java.lang.Class.getDeclaredConstructors0(Native Method)
    at java.lang.Class.privateGetDeclaredConstructors(Class.java:2389)
    at java.lang.Class.getConstructor0(Class.java:2699)
    at java.lang.Class.newInstance0(Class.java:326)
    at java.lang.Class.newInstance(Class.java:308)
    Code :
    NativeClassReader (custom) :
    public class NativeClassLoader extends ClassLoader {
        //the unique instance of the NativeClassLoader
        private static NativeClassLoader instance;
        private NativeClassLoader () {
            super(NativeClassLoader.class.getClassLoader());
         * Get the Singleton instance of the class
        public static NativeClassLoader getInstance () {
            if (instance == null)
                instance = new NativeClassLoader();
            return instance;
        public static void dispose () {
            instance = null;
         * Load a class using its full java name (prefixed with package)
        public Class findClass (String theName) {
            byte[] b = null;
            try {
                b = loadClassDataFromJar(theName);
                Class clazz = defineClass(theName, b, 0, b.length);
                resolveClass(clazz);
                return clazz;
            } catch (Exception e) {
                return null;
         * Gets the bytes of a class file stored in the current jar using
         * its full class name
        public byte[] loadClassDataFromJar (String theName)
                                     throws Exception {
            String filename = "/" + theName.replace('.', '/') + ".class";
            InputStream is = SawsApplet.class.getResourceAsStream(filename);
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            //compute file size
            Vector vChars = new Vector();
            int c;
            while ((c = br.read()) != -1)
                vChars.add(new Byte((byte) c));
            //fill in byte array with chars read from the buffer
            byte[] buff = new byte[vChars.size()];
            //workaround for a bug on one (some) Vista machine(s)
            //force magic number to CAFEBABE instead of 18635F3E
            if (vChars.size() > 3) {
                buff[0] = (byte) 0xCA;
                buff[1] = (byte) 0xFE;
                buff[2] = (byte) 0xBA;
                buff[3] = (byte) 0xBE;
            for (int i = 4; i < vChars.size(); ++i)
                buff[i] = ((Byte) vChars.get(i)).byteValue();
            return buff;
    }Reader (loading native libary) :
    public class Reader {
       static {
         System.loadLibrary("myLib");
        public static native String getData();
    }Main :
        NativeClassLoader cLoader = NativeClassLoader.getInstance();
        Class clazz = cLoader.findClass("Reader"); // ClassFormatError thrown here
        Object reader = clazz.newInstance(); // VerifyError thrown here
        Method m = clazz.getMethod("getData");
        String s = m.invoke(reader);
        print(s);
        s = null;
        m = null;
        reader = null;
        clazz = null;
        cLoader = null;
        NativeClassLoader.dispose();
        System.gcAny ideas would be really appreciated :-)
    Guillaume

    Are you using the executable exe file and the filename as a parameter in the custom task?
    Andreas Baumgarten | H&D International Group

  • JAXB 1.0 Final: jaxb.properties not found when using custom classloader

    JDK 1.3.1 is being used.
    The scenario:
    1) jaxb jar files, jaxb generated files and application files loaded in default class loader works, however
    2) jaxb jar files, jaxb generated files and application files loaded in a custom class loader generate the following exception:
    javax.xml.bind.JAXBException: Unable to locate jaxb.properties for package XXX
    To demonstrate here are two sample applications: a Launcher app whose job it is to start apps and a sample App1 application who needs JAXB.
    If launch is placed into a jar file named launch.jar and App1 is placed into a jar file named app1.jar (with a JAXB generated package), and both jar files are placed in a directory containing all the JAXB 1.0 jar files (dom, sax, namespace, etc) and the system is started with the following:
    jre\bin\java -cp launch.jar; testLaunch.launch
    the exception occurs.
    By way of comparison, if App1 is started directly with the following:
    jre\bin\java -cp app1.jar;jax-qname.jar;jaxb-xjc.jar;jaxb-ri.jar;jaxb-libs.jar;jaxb-api.jar;dom.jar;sax.jar;jaxp-api.jar;xercesImpl.jar;namespace.jar;ant.jar;xalan.jar testApp.app1
    the exception does not occur.
    Any help would be greatly appreciated.
    package testLaunch;
    import java.net.*;
    import java.io.*;
    public class launch extends javax.swing.JFrame
        private static URLClassLoader app1ClassLoader_; 
        private static Class  app1EntryClass_ = null;
        private static final String app1MainClassName_ = "testApp.app1";
        private Object appObj_ = null;
         static public void main(String args[])
              try {
                System.out.println("Launch Main");               
                new launch();          
                  System.exit(0);
              catch (Throwable t) {
                   t.printStackTrace();
                   System.exit(1);
         public launch()
            if (app1ClassLoader_== null)
                loadAppClassLoader();
            try{
                if (app1EntryClass_ == null)
                    app1EntryClass_ = app1ClassLoader_.loadClass(app1MainClassName_);
                if (app1EntryClass_ == null)
                    System.out.println(app1MainClassName_ + " was not found");
                else
                    appObj_ = app1EntryClass_.newInstance();
            catch(ClassNotFoundException x){
                x.printStackTrace();
            catch(Exception x){
                x.printStackTrace();
        private static void loadAppClassLoader()
            String jarPath = jarPath = System.getProperty("user.dir");
            System.out.println("jar path is: " + jarPath);
            try{
                File jarfile1 = new File(jarPath+File.separator+"app1.jar");
                File jarfile2 = new File(jarPath+File.separator+"dom.jar");
                File jarfile3 = new File(jarPath+File.separator+"jaxp-api.jar");
                File jarfile4 = new File(jarPath+File.separator+"jaxb-api.jar");
                File jarfile5 = new File(jarPath+File.separator+"jaxb-xjc.jar");
                File jarfile6 = new File(jarPath+File.separator+"jaxb-ri.jar");
                File jarfile7 = new File(jarPath+File.separator+"jaxb-libs.jar");
                File jarfile8 = new File(jarPath+File.separator+"jax-qname.jar");
                File jarfile9 = new File(jarPath+File.separator+"sax.jar");
                File jarfile10 = new File(jarPath+File.separator+"xercesImpl.jar");
                File jarfile11 = new File(jarPath+File.separator+"namespace.jar");
                File jarfile12 = new File(jarPath+File.separator+"xalan.jar");
                File jarfile13 = new File(jarPath+File.separator+"ant.jar");
                if (!jarfile1.exists())
                    System.out.println("**ERROR " + jarfile1 + " does not exist!");
                app1ClassLoader_ = new URLClassLoader( new URL[]{jarfile1.toURL(),
                                                                jarfile2.toURL(),
                                                                jarfile3.toURL(),
                                                                jarfile4.toURL(),
                                                                jarfile5.toURL(),
                                                                jarfile6.toURL(),
                                                                jarfile7.toURL(),
                                                                jarfile8.toURL(),
                                                                jarfile9.toURL(),
                                                                jarfile10.toURL(),
                                                                jarfile11.toURL(),
                                                                jarfile12.toURL(),
                                                                jarfile13.toURL()} );
            catch(Exception x){
                x.printStackTrace();
                return;
    package testApp;
    import javax.xml.bind.*; // JAXB classes
    import myGeneratedJAXBFiles;
    public class app1 extends javax.swing.JFrame
         static public void main(String args[])
              try {
                System.out.println("App1 Main");               
                new app1();           
                  System.exit(0);
              catch (Throwable t) {
                   t.printStackTrace();
                   System.exit(1);
         public app1()
            try
                JAXBContext jc_ = JAXBContext.newInstance( "myGeneratedJAXBFiles" );
                System.out.println("Successfully loaded JAXB Context");          
            catch (JAXBException jbe)
                jbe.printStackTrace();

    I'm doing something very similar. In fact my launcher is also stored in launcher.jar. It will start any application on the classpath and load dependencies jars located in the specified directory.
    The first thing you must do is specify the classloader when constructing the jaxb context:
    JAXBContext jc = JAXBContext.newInstance(xmlPackage, getClass().getClassLoader());
    After this I was still raning into the "jaxb.properties not found" exception in some situations. Basically if the class using the jaxb files is located in the same jar as jaxb.properties everything worked fine. However if the class using the jaxb objects was located in a different jar it did not work.
    I had to add the following early in the execution of the application that load the plugins to get things working correctly:
    Thread.currentThread().setContextClassLoader(jarDirClassLoader);
    As far as I can tell JAXB using the Context class loader to find the jaxb.properties file.
    I'm using JAXB 1.1
    I hope this helps!

  • Best way to call custom classloader

    I have created a custom classloader to perform hot deployment for application server. How do I let JVM to use my class loader instead of system class loader?
    a. Using the command line argument -Djava.system.class.loader
    b. Using -javaagent and setting System.setProperty("java.system.class.loader", myclass) in premain method.
    c. Is there any other alternative?
    If I am using the command line approach, I will need to have my jar file in the classpath. What is the best way to do this?
    Thanks for your help

    Or you could write a small program which sets up the classloader and then loads the target program with it.

  • Custom ClassLoader - trying to use different version of SNMP library than WebLogic Server 8.1 uses

    Problem: my J2EE ear file uses the AdventNet third-party library to do
    SNMP work. WebLogic Server 8.1 also uses this AdventNet third-party
    library to do its own SNMP work. The problem is the version used by
    WebLogic 8.1 is older than the version I use, so my code tries to run
    and finds the wrong version of the library that WebLogic 8.1 has supplied.
    Possible solution: I plan to have a custom classloader (derived from
    java.lang.ClassLoader) that gets hooked in to my threads using
    Thread.setContextClassLoader(). This custom classloader would look for
    the AdventNet library jars in a spot I specify so it would find the
    correct ones. Since I want to change the usual classloader behavior of
    "look in parent classloaders first, then child classloader" to "look in
    child classloader first, then in parent classloaders" I can't just
    override ClassLoader.findClass(). I, at a minimum, have to override
    ClassLoader.loadClass() to look in my classloader first. I have
    questions about this:
    1. What other methods do I have to override? For example, which of the
    resource-related methods do I need to override so that resources are
    searched for first in my classloader then in parent classloaders?
    2. I was thinking of using a URLClassLoader as a helper to my
    classloader, invoking its method(s) from my custom classloader's
    method(s) to actually load the classes from URLs that are not on the
    standard classpath. I was planning to set it up with a custom parent
    classloader that can't find anything, so that the helper URLClassLoader
    would only ever find classes/resources in the URLs I provide to it. Does
    this approach make sense? Have you seen anything like this done before?
    3. Is there any way around this problem besides a custom ClassLoader? A
    buggy custom ClassLoader would have problems which AFAIK would be
    difficult to track down as ClassLoader problems.
    Thanks in advance for any help you can provide.

    Alvin wrote:
    Hi,
    I am experiencing the same problme and
    even I tried to put the AdventNet jar files
    before weblogic.jar I still cannot get it
    to work
    Would you help me out here.
    Thanks,
    -AlvinI finally figured out a way to do it using a custom classloader that
    looked in the directory where I kept the version of AdventNet I wanted
    before looking in the normal places classloaders look.
    How it works is I hook two classloaders at the bottom of the chain of
    classloaders. My custom BlockingClassLoader is hooked as a child of the
    normal chain of classloaders, then a URLClassLoader is hooked under
    that. The BlockingClassLoader's findClass method checks if the class
    starts with a package prefix I want to control (like "com.adventnet.").
    If it does, then it acts like it can't find the class. This makes its
    child, the URLClassLoader, try to find the class. The URLClassLoader
    is given the URL of places to look for classes that match the directory
    I keep the version of AdventNet I want in. When I load a class, I
    directly tell the URLClassLoader to load it so that it is loaded as I want.
    There's more to it than this. I had to override some other methods in
    my BlockingClassLoader and do some other stuff. I'm not sure if I can
    share the source code, as it was developed on company time and thus is
    owned by the company. Feel free to ask questions though.
    I haven't tried this solution very long (basically just unit tested it)
    but it looks promising.

  • Custom classloader in Applet?

    Hi
    I have for some time tried to load an Applet from within an Applet by means of custom classloader.
    However when reading various specifications for classloader they state it is not possible for an Applet to do so.
    Does anyone know otherwise?

    Hi
    To be more specific.. I have 2 Applets yes. In the first signed Applet I run as a jar I have created a custom classloader that extends ClassLoader hence the java bytecode I wish to load (also an Applet) must be (a) class file(s). As far as I know the ClassLoader is not able to define classes from jars right?
    It is only the loading Applet that is packed as a jar and there is no nested jars. However the loaded Applet is now loaded as a class file but I would like to load is a jar for speeding up loading time.
    Quote from http://www.javaworld.com/javaworld/jw-10-1996/jw-10-indepth.html:
    There is a cost, however, because the class loader is so powerful (for example, it can replace java.lang.Object with its own version), Java classes like applets are not allowed to instantiate their own loaders. (This is enforced by the class loader, by the way.) This column will not be useful if you are trying to do this stuff with an applet, only with an application running from the trusted class repository (such as local files).

Maybe you are looking for

  • Streaming video to tv

    Strange glitch--pls help. Yesterday, I bought an hdm cord and adapter so it would fit into my MacBook Air. I also bought a separate speaker system. When I set it up, it worked perfectly. I had to disconnect my MacBook and when I set everything up, it

  • Char and Attributes

    Hi all, I am having a requirement wer i need to create the report which include the fields PO line item, PO del. date, PO LOI date, and some other char Now can i create the PO line item and char and PO del dat, PO LOI dat as attributes of it. Does it

  • Oracle RAC 10g R2 And SUSE SLES10

    Hi there guys I downloaded oracle rac 10 R2 and tried to install it using OpenSuse Linux 10.1 which resulted in an unsoported OS error.. the documentations says about SLES9 which I do not have, my provider has SLES10, I'd like to know is If need SLES

  • Creative 30g Nomad Zen Nx With Vista Problems.

    I am so peed off. I just brought a brand new laptop from Comet with Vista here in the UK and have just realised I cannot use it with my zen nx 30gb mp3 player! Why on earth is there no new drivers for it or a simple way to get around it! My mp3 playe

  • Do I have a virus on my iPhone4? I get new same ad boxes in 2 old game apps

    Happy New Year to everybody! I have an iPhone 4. I checked the questions regarding Viruses on iPhones, but could not find the same case as mine. Around Christmas, I downloaded a few apps and deleted some of them again. Among those I kept were the Rum