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.

Similar Messages

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

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

  • Can't use custom ClassLoader with ObjectInputStream

    Hi all,
    I want to transmit an object whose class is unknown to the receiver and whose class may not be loaded. Of course when the inputstream's readObject method tries to receive this class, it fails with a ClassNotFoundException. I have a custom FileClassLoader to dynamically load classes, this is tested and works.
    I can dynamically load this class and prove that the class was loaded by calling class.newInstance() from the loader.loadClass method. But then when I try to read that same class from the input stream, it says ClassNotFoundException!
    The code snippet looks like this:
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    FileClassLoader loader = new FileClassLoader(classFolder);
    Class L = loader.loadClass(className); // no .class at end
    System.out.println("New Instance "+L.newInstance().toString()); // works
    ObjectInputStream eventStream = ... // stream from a socket
    eventStream.readObject(); // throws class not found exception!
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    The only thing I can think is that the input stream only looks for classes loaded by the system classloader, could that be true? What other possibilities are there?
    If this is more appropriate for another forum just let me know and I'll post it there.
    Thanks in advance for any helpful hints anybody has!

    I was thinking of something along the lines of
    ObjectInputStream eventStream = (ObjectInputStream)Class.forName("java.io.ObjectInputStream", true, loader).newInstance();Of course, you would really have to get the proper Constructor for the class - and that just gets too long and stupid. Besides, I actually tried my suggestion, and it didn't work. I also tried setting the ContextClassLoader for the current thread (and creating a new thread with the ContextClassLoader set to "loader"). None of that works. Just setting the ContextClassLoader does not make the thread use it implicitly, it's apparently just a way to pass another ClassLoader to a thread, but it still needs to be used explicitly in a Class.forName call.
    I did, however, try David's suggestions of overriding resolveClass in ObjectInputStream. That worked fine! Here's what I created:
    import java.net.URLClassLoader;
    import java.io.InputStream;
    import java.io.IOException;
    import java.io.ObjectInputStream;
    import java.io.ObjectStreamClass;
    import java.io.StreamCorruptedException;
    public class MyObjectInputStream extends java.io.ObjectInputStream
        URLClassLoader myLoader = null;
        public MyObjectInputStream(URLClassLoader newLoader, InputStream theStream) throws IOException, StreamCorruptedException
            super(theStream);
            myLoader = newLoader;
        protected Class resolveClass(ObjectStreamClass osc) throws IOException, ClassNotFoundException
            System.out.println("Hey, I'm in my resolveClass");
            Class theClass = null;
            try
                theClass = Class.forName(osc.getName(), true, myLoader);
            catch (Exception e)
                System.err.println("An Error in my ResolveClass:");
                e.printStackTrace();
            return theClass;
    }You then just create your ObjectInputStream with
    ObjectInputStream eventStream = new MyObjectInputStream(loader, theSocket.getInputStream());

  • 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

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

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

  • Using custom classloader with javac

    There is an interesting thread going on at http://forums.java.net/jive/thread.jspa?threadID=13417&tstart=0.
    Since this forum seems to be more active than that forum, I wonder if anyone has an answer to my last post on that thread (post number 4 by garyh)?
    Thanks for any help.

    Please ignore this post.
    It was submitted before I finished writing it.
    Sorry,
    zganon

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

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

  • 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

  • XMLEncoder stackoverflow problem with custom classloader

    Hi, All
    I'm tring encoding my object using XMLEncoder, the objects are from the custom classloader like URLClassLoader which is importing several jar files at run-time.
    source code is like this:
    XMLEncoder e = new XMLEncoder(new BufferedOutputStream(os));
    e.writeObject( sourceObj);
    When I run it, I experienced this error:
    XMLEncoder has "ClassNotFoundException" or "InstantiationException" problem.
    so I found very similar posting for this problem and modified it so that the XMLEncoder can find my classes from custom classloader:
    ClassLoader cl = this.getClass().getClassLoader();
    URLClassLoader urlClassLoader = new URLClassLoader(urls, cl);
    Thread.currentThread().setContextClassLoader(urlClassLoader);
    XMLEncoder e = new XMLEncoder(new BufferedOutputStream(os));
    e.writeObject( sourceObj);
    The result was slightly changed. However, still disappointing:
    java.lang.StackOverflowError
         at java.lang.Class.getMethod0(Class.java:1734)
         at java.lang.Class.getMethod(Class.java:951)
         at java.beans.Statement.findPublicMethod(Statement.java:230)
         at java.beans.Statement.findMethod(Statement.java:270)
         at java.beans.Statement.getMethod(Statement.java:366)
         at java.beans.Statement.invoke(Statement.java:439)
         at java.beans.Expression.getValue(Expression.java:101)
         at java.beans.Encoder.getValue(Encoder.java:84)
         at java.beans.Encoder.get(Encoder.java:186)
         at java.beans.PersistenceDelegate.writeObject(PersistenceDelegate.java:97)
         at java.beans.Encoder.writeObject(Encoder.java:55)
         at java.beans.XMLEncoder.writeObject(XMLEncoder.java:250)
         at java.beans.Encoder.writeExpression(Encoder.java:260)
         at java.beans.XMLEncoder.writeExpression(XMLEncoder.java:351)
         at java.beans.PersistenceDelegate.writeObject(PersistenceDelegate.java:100)
         at java.beans.Encoder.writeObject(Encoder.java:55)
         at java.beans.XMLEncoder.writeObject(XMLEncoder.java:250)
         at java.beans.Encoder.writeExpression(Encoder.java:260)
         at java.beans.XMLEncoder.writeExpression(XMLEncoder.java:351)
         at java.beans.PersistenceDelegate.writeObject(PersistenceDelegate.java:100)
         at java.beans.Encoder.writeObject(Encoder.java:55)
         at java.beans.XMLEncoder.writeObject(XMLEncoder.java:250)
         at java.beans.Encoder.writeExpression(Encoder.java:260)
         at java.beans.XMLEncoder.writeExpression(XMLEncoder.java:351)
         at java.beans.PersistenceDelegate.writeObject(PersistenceDelegate.java:100)
         at java.beans.Encoder.writeObject(Encoder.java:55)
    When I finally include the jar files into the classpath so that the default classloader can reference them, the encoder worked properly.
    Anyone can help me?

    StackOverFlow is quite a gotcha in XMLEncoder it is often because of the following code in java.beans.PersistenceDelegate:
    public void writeObject(Object oldInstance, Encoder out) {
    Object newInstance = out.get(oldInstance);
    if (!mutatesTo(oldInstance, newInstance)) {
    out.remove(oldInstance);
    out.writeExpression(instantiate(oldInstance, out));
    else {
    initialize(oldInstance.getClass(), oldInstance, newInstance, out);
    and the following code in java.beans.DefaultPersistenceDelegate:
    protected boolean mutatesTo(Object oldInstance, Object newInstance) {
    // Assume the instance is either mutable or a singleton
    // if it has a nullary constructor.
    return (constructor.length == 0) || !definesEquals(oldInstance) ?
    super.mutatesTo(oldInstance, newInstance) :
    oldInstance.equals(newInstance);
    What this means is if you have a class (you want to persist) that has a constructor that takes arguments AND defines an equals method AND you have overridden initialize in DefaultPersistenceDelegate to do some extra work after it instantiates newInstance, then while the PersistenceDelegate is trying to generate you newInstance, oldInstance.equals(newInstance) will return false, and PersistenceDelegate will keep trying to instantiate a newInstance that does equal the oldInstance.
    So if you do use DefaultPersistenceDelegate then ensure that you override mutatesTo so that it is:
    protected boolean mutatesTo(Object oldInstance, Object newInstance) {
    return (newInstance != null && oldInstance.getClass() == newInstance.getClass());
    Here is an example PersistenceDelegate that persistence a class called PersistentBeanCollection, it calls its constructor with the property "type" and then calls the method add() on the newInstance.
    new DefaultPersistenceDelegate(new String[]{"type"}) {
    protected void initialize(Class type, Object oldInstance, Object newInstance, Encoder out) {
    PersistentBeanCollection oldBeanCollection = (PersistentBeanCollection) oldInstance;
    for (Iterator iterator = oldBeanCollection.iterator(); iterator.hasNext();) {
    out.writeStatement(new Statement(oldInstance, "add", new Object[]{iterator.next()}));
    protected boolean mutatesTo(Object oldInstance, Object newInstance) {
    return (newInstance != null && oldInstance.getClass() == newInstance.getClass());
    Cheers
    Parwy

  • Detecting when exception was thrown using custom class loader

    Hello all,
    I would like to implement the solution described here - http://stackoverflow.com/questions/75218/how-can-i-detect-when-an-exceptions-been-thrown-globally-in-java - that uses custom class loader in order to detect when an Exeption thrown somewhere in the JVM hosting my app, please note that exceptions might be thrown from 3rd party jars the app is using. So, thanks to help I got from another post, I've managed to code the custom class loader. My question is how can the class loader wrap the original exception, as the methods in ClassLoader deals with classes, not instances. So where should I set the original exception?
    Thanks!
    Edited by: user9355666 on Sep 28, 2010 10:48 PM

    user9355666 wrote:
    I think I'm missing something fundumental, forgive me for being slow...
    This is what I did so far. For the exception wrapper I made a simple class extens Exception that recieve Exception in its ctor and store it. I also subclassed ClassLoader and override its loadClass(). I've registered it as the system classloader. My thinking was to check in that point that if the requested class is instance of Exception and if yes, returning my wrapper class wrapping this exception. But, since loadClass() return class, how can I set in the wrapper the original exception?
    In addition, let's say 2 different places in the code throws NPE, to my understanding the classloader will load NPE only once, so how throwing the NPE in the second time can be detected?you are missing a key point. you should creating a custom implementation of the NPE class which hooks into your detection code in its constructor. from that point forward, anytime any NPE (which is your custom class) is constructed, you can detect it.

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

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

Maybe you are looking for

  • Multiple dataset problems with ie

    Hi You all; I have been having an bug that accures only on IE. I have a two dataset that is tied to a region. One display values and one checks to see what to display. here is a snippet: <div spry:region="rsTop2merchants rsWatchMerchant pvMerchantite

  • Getting external swf to stay visible?

    Hi I have an external swf that contains a button that controls my main swf's timeline. I can get it to navigate fine, but as soon as it navigates, my external swf disappears, because my main swf is no longer on the frame my external swf was imported

  • Using attributes in a Query, doesnu00B4t work!

    I have implemented an infocube 0SD_C03, and i have my material attributes filled in the 0MATERIAL characteristic, but when i use them in the query, the don't appear. Can somebody help me? Thank You

  • Error in connect to Enterprise manager console

    I am getting the following error message when trying to connect to oracle 9i Enterprise manager console with the following username and password: sysoper/oem_temp as sysoper AND sys/password as sysdba Error Message :ORA12532:TNS:Invalid arguement I i

  • Iweb site not publsishing

    Can anyone tell me why -twice in the past several days- my iweb website won't publish? Is this a MobileMe problem? I been publishing this site in the same way with no problems for over two years?