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));
}

Similar Messages

  • 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.

  • Implementing a custom ClassLoader

    Hi. I have found plenty of tutorials online about how to create your own custom ClassLoader but how do you actually go about indicating to the JVM that it should be using a custom ClassLoader for a given application? I can't figure it out.

    It's quite interesting. Often I find that inquiries on ClassLoader are related to the poster's misunderstanding something, but yes, sometimes interesting things come up.
    I want
    to contrive some sort of mechanism for embedding java
    code or some custom templating language in HTML. Hmm, like JSP?
    I want to avoid having to recompile my whole
    application each time i or someone else updates an
    HTML template. It seems that a custom classloader is
    the answer here where i could write a custom loader
    that would detect recently modified HTML templates
    and re-compile their associated .class file on the
    fly before re-loading the class.I wrote one of these along time ago. Its a bit tricky, but its been done.
    Why reinvent the wheel? I believe you could find one by doing a google for
    DynamicClassLoader.
    Take a look at janino, too.
    Good luck.

  • 5.1 SP8 Custom ClassLoader ClassFormatError messages

    We use a custom ClassLoader that unscrambles classfiles not understood by its parent.
    When the Weblogic parent ClassLoader attempts discovers it can't decipher the
    file, it writes a ClassFormatError message and stack trace to the console (though
    not to the log) before delegating to its child (our code) which proceeds to load
    the class with no trouble. The result is that our product runs fine, but appears
    to be full of unloadable classes. How can we get the Weblogic ClassLoader to suppress
    these misleading error messages? (IMHO, it shouldn't report errors until and unless
    both it and its child have failed, but given that it does, is there some way to
    make it shut up?)

    You can use class preprocessor in WebLogic for that sort of thing (products
    like Wily and Tangosol use this feature to instrument or customize classes when
    they are loaded by WebLogic classloaders) without adding your own classloaders,
    for example, in 6.1:
    public class ExamplePreprocessor implements weblogic.utils.classloaders.ClassPreProcessor {
    public void initialize(java.util.Hashtable ht) {}
    public byte[] preProcess(String classname, byte[] classbytes) {
         ... unscramble or do whatever is that you do with classbytes ...
    return classbytes;
    and add this to the WebLogic command line :
    -Dweblogic.classloader.preprocessor=preprocessorclassname
    Jonathan Shultis <[email protected]> wrote:
    We use a custom ClassLoader that unscrambles classfiles not understood by its parent.
    When the Weblogic parent ClassLoader attempts discovers it can't decipher the
    file, it writes a ClassFormatError message and stack trace to the console (though
    not to the log) before delegating to its child (our code) which proceeds to load
    the class with no trouble. The result is that our product runs fine, but appears
    to be full of unloadable classes. How can we get the Weblogic ClassLoader to suppress
    these misleading error messages? (IMHO, it shouldn't report errors until and unless
    both it and its child have failed, but given that it does, is there some way to
    make it shut up?)--
    Dimitri

  • WAR within EAR is using the same classloader as the EAR

    Hi all,
    From documentation, I understand that each WAR web application that are packaged within EAR should have a separate (child) classloader and should not be using the same classloader as the EAR. I have two WAR files and some JAR files all packaged and deployed as an EAR. Using the Classloader Analysis Tool, I think the two web applications (WARs) are actually using the same classloader as the EAR. I say this because:
    1. The application class loader listed for the web apps has the same hashcode as the class loader listed for the EAR.
    2. I tried to add the <prefer-web-inf-classes> element within the WAR's weblogic.xml file and it doesn't seem to work. The web app is still using classes loaded in the EAR. This is consistent with my observation that the classloader for the WARs has the same hashcode as the classloader for the EAR - therefore I think they are using the same classloader.
    I don't understand this behavior. I thought WARs are supposed to be using different/child classloaders from the EAR by default. Do I have to specifically declare my own customer <classloader-structure> within weblogic-application.xml in order to have child classloaders for the WARs within my EAR?
    Thanks for any help.

    We are doing it currently as we are switching over from Exchange 5.5 to OCS. We set up a profile using the Oracle connector and then go into properties and add the Exchange account. We used this method to move files from the Exchange server to the Oracle server by having both profiles running.

  • 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 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?

  • Annotation-Processing Using Custom ClassLoader Fails

    Hi,
    I have the following problem concerning annotations.
    I am using Jaxb2 to marshal some classes and Jaxb relies heavily on processing annotation information contained in them.
    If I put the Jaxb JAR's directly in the classpath everything works fine.
    However, if I use a custom URLClassLoader to load all the Jaxb-related classes the annotation processing fails thus making Jaxb believe that the objects can't be marshaled.
    Note that the classes to marshal containing the annotations to read are loaded with a different ClassLoader which is higher in the hierarchy.
    I tracked down the problems to the class RuntimeInlineAnnotationReader of the Jaxb API which simply calls Class.getAnnotion(..).
    When searching for this bug I also found the bug report 5015623 which relates to this problem. But it is rather outdated, so I hope that there are some better solutions than just ignoring it.
    I wouldn't like having the Jaxb JARs on the global classpath 'cause they are used in only one class out of 100 and thats not worth the possible conflicts with other 3rd party libs.
    Best regards,
    beebop

    No problem, I will give you some details about my architecture.
    First of all I encapsulated the code which uses the Jaxb-API in one class, say Foo, which implements the interface FooInterface.
    Secondly I load the Foo class in another class, Bar, using my derivation of URLClassLoader, called MyClassLoader. Then I use the interface to marshal an object gen of type GenClass where GenClass was generated using xjc:
    class Bar {
      void method(URL[] urls, GenClass gen) {
        ClassLoader parent = Bar.class.getClassLoader();
        ClassLoader myCL = new MyClassLoader(urls,parent);
        Class clazz = myCL.loadClass("Foo");
        FooInterface foo = (FooInterface)clazz.newInstance();
        foo.marshal(gen);
    }So my class loader will be a child of the current class loader. The delegation model of class loading is reversed in MyClassLoader so that first the urls will be checked and then, if the class was not found, the parent class loader.
    Note that GenClass and its ObjectFactory which acutally contain the annotations Jaxb needs will be loaded by the current class loader, not my own. All classes of the Jaxb-API will be loaded by MyClassLoader. If I try to marshal gen, the annotations of the ObjectFactory corresponding to GenClass won't be readable causing the Class.getAnnotation(...) method called in the class RuntimeInlineAnnotationReader to return null.
    If I don't use my own class loader, say
    FooInterface foo = new Foo();everything works fine and the annotations of the ObjectFactory are loaded correctly.
    I observed the different behaviour by stepping through the classes and methods around JaxbContext.newInstance(...).
    MyClassLoader is not that different from URLClassLoader, only the loadClass method is overridden to change the delegation behaviour. Thats why I suspect an error in the annotations framework and not in my class loader but I may be mistaken.
    Best regards,
    beebop

  • 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.

  • Complie time using custom classloader for decryption.

    I need to decrypt several class during compile time, but my custom classloader could load everything except my encrypted classes.
    Here is my sample code and how I test it.
    Test.java:
    public class Test {
         public Test(){
              System.out.println("test");
         public void hello(){
              System.out.println("hello");
    Test1.java
    public class Test1 extends java.lang.Test{
         public Test1(){
              System.out.println("test1");
         public static void main(String[] args){
              new Test1().hello();
    #EncryptedClassLoader will print out the class name it trying to load, for example: "load class: java.lang.System"
    1. Compile Test.java file and have it encrypted, make it into a jar file - test.jar.
    2. Compile Test1.java file and try to run Test1.class with encrypted Test.class file using :
    C:\lib>java -Djava.system.class.loader=EncryptedClassLoader -classpath c:\lib;c:\lib\tools.jar;c:\lib\test.jar Test1
    Gives the output:
    load class: java.lang.System
    load class: java.nio.charset.Charset
    load class: java.lang.String
    load class: Test1
    load class: Test
    load class: sun.security.provider.Sun
    load class: sun.security.rsa.SunRsaSign
    load class: com.sun.net.ssl.internal.ssl.Provider
    load class: com.sun.crypto.provider.SunJCE
    load class: java.lang.Object
    load class: java.io.PrintStream
    test
    test1
    hello
    So now I'm sure there's no problem with my EncryptedClassLoader
    3. Try to compile Test1.java with the encrypted Test.class in test.jar(These's no Test.java file in the same folder) by using:
    C:\lib>javac -J-Djava.system.class.loader=EncryptedClassLoader -J-classpath -J.;c:\lib;c:\lib\tools.jar;c:\lib\test.jar Test1.java
    Give the output:
    .............. (loading several system classes)
    load class: com.sun.tools.javac.util.Position
    Test1.java:4: cannot find symbol
    symbol: class Test
    public class Test1 extends Test{
    ^
    load class: java.lang.Long
    load class: java.io.DataInputStream
    load class: com.sun.tools.javac.jvm.ClassReader$AnnotationCompleter
    load class: com.sun.tools.javac.jvm.ClassReader$AnnotationDeproxy
    load class: com.sun.tools.javac.jvm.ClassReader$ProxyVisitor
    load class: com.sun.tools.javac.code.Types$SubstFcn
    load class: com.sun.tools.javac.code.BoundKind
    load class: java.lang.StringBuffer
    Test1.java:12: cannot find symbol
    symbol : method hello()
    location: class Test1
    new Test1().hello();
    ^
    2 errors
    ---> from the output I found that Test.class never visited/loaded by my EncryptedClassLoader
    Though I set EncryptedClassLoader as the default system classloader but it seems to load everything except my encrypted class.
    Does anyone know why it works like this??
    Thank you in advanced,
    Alex.
    null

    I don't know why he was specifying the javac classpath like that instead of using javac's -classpath option.
    But this whole business of decrypting class loades is pretty much a waste of time. It adds a layer of comfort but it's not really what I would call secure. At some point the unencrypted bytes have to appear in memory and from that point the classes are no longer secure.
    The best protection against software piracy is not anti-decompilation techniques but time-to-market and pricing your product so that buying it is cheaper than reverse-engineering it.

  • Using custom ClassLoader

    Is there a way to make my custom ClassLoader the default ClassLoader for my program?
    ie. Can I just set up my program to use my ClassLoader whenever it needs to access class files?
    Geoff.

    Hi,
    The main class is always loaded by the boot strap class loader(also called System ClassLoader). You can't change it. After that all the classes are loaded by the classloader of the loading class. i.e.
    If class A is loading class B, then class B's classloader will be the classloader of class A.
    So, basically you need to write a classloader, and a wrapper class for your main class like:
    public class WrapperClass
        public void main(String[] args) throws Exception
           MyClassLoader myClassLoader = new MyClassLoader();
           Class mainClass = myClassLoader.loadClass("MainClass");
           Method mainMethod = mainClass.getMethod("main", new Class[] {args.getClass()});
           mainMethod.invoke(null, args);
    }then rest of the classes including MainClass are loaded by the MyClassLoader. If you need help you writing ClassLoader please reply back.
    Hope this helps.

  • Custom classloader fails when using Java Web Start

    Hope you can help me with a problem that is driving me nuts. I have implemented my own classloader to support plugins. This classloader works as follows:
    1. The classloader is configured to access a plugin components jar file downloaded by jws.
    2. The plugin components jar file contains other jar files which contains the actual plugin code to be loaded using my own classloader.
    3. Upon initialization - my classloader extracts all jar files contained in the plugin components jar file into temporary files.
    4. These temporary files are used by my classloader when defining plugin classes.
    The classloader works fine when not using java web start. Then I launch the application using java web start with security policy in .jnlp file set to:
    <security>
    <all-permissions/>
    </security>
    After a while (it was able to load some of the classes) it fails with the following stack-trace:
    Regards,
    Terje
    java.security.AccessControlException: access denied (java.io.FilePermission C:\DOCUME~1\TEOES\LOCALS~1\Temp\activity61102.jar read)
         at java.security.AccessControlContext.checkPermission(Unknown Source)
         at java.security.AccessController.checkPermission(Unknown Source)
         at java.lang.SecurityManager.checkPermission(Unknown Source)
         at java.lang.SecurityManager.checkRead(Unknown Source)
         at java.util.zip.ZipFile.<init>(Unknown Source)
         at java.util.jar.JarFile.<init>(Unknown Source)
         at java.util.jar.JarFile.<init>(Unknown Source)
         at my.plugin.ActivityClassLoader.getJarFileEntry(ActivityClassLoader.java:258)
         at my.plugin.ActivityClassLoader.search(ActivityClassLoader.java:244)
         at my.plugin.ActivityClassLoader.loadClass(ActivityClassLoader.java:99)
         at java.lang.ClassLoader.loadClass(Unknown Source)
         at java.lang.ClassLoader.loadClassInternal(Unknown Source)
    Does anyone have source code for implementing a simple class loader that can be used with Java Web Start (preferrably with all jar files to be used by the classloader wrapped into a jar file)

    If you implement your own classloader, and then still run with a SecurityManager installed, then your ClossLoader is responsible for asigning the permissions to the code it loads.
    You need your ClassLoader to extend SecureClassLoader, and implement the method :
    SecureClassLoader.getPermissions(CodeSource cs) to return the PermissionCollection you want.
    /Andy

  • Single EAR multiple WAR model - faces-config not loading

    Hi
    I am deploying my application on weblogic 10.3 My application is in form of a Single-EAR-Multiple-WAR model. The application starts up correctly but when i bavigate from one module (WAR) to another (WAR), it doesnt initializes the managed beans. It is not able to load the faces-config from the second WAR.
    can anyone please let me know ehat am i missing?
    Thanks a lot
    -Ankur

    Hi,
    This is not an issue caused by having multiple wars inside same ear.
    This looks like a runtime exception when trying to render the jsp (The jsp is compiled to a sevlet and the inside the service method of the servlet you are getting this exception). Double check you jsp for the possible cause of this exception.
    Thanks,
    Gopinath Ramasamy

  • 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

  • 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

Maybe you are looking for

  • Windows 10 Preview on Dell Venue 11 Pro Tablet

    Windows 10 Preview on Dell Venue 11 Pro Hardware Dell Venue 11 Pro (7130/7139) tablet computer with: Intel Core I3 4020Y processor (3MB Cache, 1.5GHz Dual-Core) 4GB 1600MHz memory. 128GB SSD. Lexar 64GB MicroSD memory card. Lexar 64GB USB memory card

  • I/O Assistant Query and Parse problem.

    Hi, I am trying to use the I/O assistant with Instrument via the serial port (com1). When I use the query and parse option it only grabs the first line and parses it. For example, my command is "gc", my instrument by nature will echo that back to ser

  • Exporting .mov to H264 in Quicktime Pro not working for iPad!

    Good morning All, Thanks for your help. When I take video's with my digital camera it records in Quicktime, however I have always had to export the videos with QuicktimePro in the H264 codec for them to transfer to my iPhone. What is happening with t

  • Firefox doesn't pass vCalendar downloads to Outlook correctly.

    Setup Firefox to associate .vcs files with Outlook (not save to file,) and download a calendar entry from a web site such as United.com. When you confirm the download, Outlook will start and display an "Invalid command line entered, please check your

  • Garritan Personal Orchestra on Intel Macs?

    Hi folks... Before I buy the Garritan Personal Orchestra for my Macbook Pro, I was wondering if any users know whether how this would run on an intel mac, (I have not used any non-Logic plug ins before). It doesnt appear to be availbale in universal