Class loader & instantiate

hi there;
i know the concept of class loader & instantiate working. may i know, what is the best situation to use <class loader> or <instantiate> method? i am currently being confused by this method. appreciate if you can give scenario to describe?
thanks in advance.
rgds;
yoke yew

http://java.sun.com/docs/books/tutorial/java/concepts/index.html

Similar Messages

  • Dynamic class loading problem using unknown JAR archive and directory names

    I read the following article, which enlightened me a lot:
    Ted Neward: Understanding Class.forName().
    However, it took me some while to understand that my problem is the other way around:
    I know the name of the class, I know the name of the method,
    but my program/JVM does not know where to load the classes from.
    Shortly, my problem is that the server engine that I am writing
    uses two different versions of the same library.
    So I am trying out the following solution:
    My program is named TestClassPathMain.java
    Assume the two libraries are named JAR1.jar and JAR2.jar
    and the class/instance method that should
    be exposed to TestClassPathMain.java by them is named
    TestClass1.testMethod().
    As long as I was depending on just one library,
    I put JAR1.jar in the classpath before starting java,
    and I was happy for a while.
    At the moment I got the need to use another version of
    TestClass1.testMethod() packaged in JAR2.jar,
    a call would always access JAR1.jar's
    TestClass1.testMethod().
    I then decided to remove JAR1.jar from the classpath,
    and programmatically define two separate ClassLoaders, one for use
    with JAR1.jar and the other for use with JAR2.jar.
    However, the problem is only partly solved.
    Please refer to the enclosed code for details.
    (The code in the JAR1.jar/JAR2.jar is extremely simple,
    it just tells (by hardcoding) the name of the jar it is packaged in
    and instantiates another class packaged in the same jar using
    the "new" operator and calls a method on it. I don't enclose it.)
    The TestClassPathMain.java/UC1.java/UC2.java code suite was
    successfully compiled with an arbitrary of JAR1 or JAR2 in the classpath,
    however removed from the classpath at runtime.
    (I know that this could have been done (more elegantly...?) by producing an Interface,
    but I think the main problem principle is still untouched by this potential lack of elegancy(?))
    1) This problem should not be unknown to you experts out there,
    how is it generally and/or most elegantly solved?
    The "*** UC2: Variant 2" is the solution I would like best, had it only worked.
    2) And why arent "*** UC2: Variant 2" and
    "*** static UC2: Variant 2" working,
    while "*** Main: Variant 2" is?
    3) And a mal-apropos:
    Why can't I catch the NoClassDefFoundError?
    The output:
    *** Main: Variant 1 JAR 1 ***:
    Entering TestClass1.testMethod() packaged in JAR1.jar
    About to instantiate TestClass2 with the new operator
    About to call TestClass2.testMethod()
    Entering TestClass2.testMethod() packaged in JAR1.jar
    *** Main: Variant 1 JAR 2 ***:
    Entering TestClass1.testMethod() packaged in JAR2.jar
    About to instantiate TestClass2 with the new operator
    About to call TestClass2.testMethod()
    Entering TestClass2.testMethod() packaged in JAR2.jar
    *** Main: Variant 2 JAR 1 ***:
    Entering TestClass1.testMethod() packaged in JAR1.jar
    About to instantiate TestClass2 with the new operator
    About to call TestClass2.testMethod()
    Entering TestClass2.testMethod() packaged in JAR1.jar
    *** Main: Variant 2 JAR 2 ***:
    Entering TestClass1.testMethod() packaged in JAR2.jar
    About to instantiate TestClass2 with the new operator
    About to call TestClass2.testMethod()
    Entering TestClass2.testMethod() packaged in JAR2.jar
    *** UC1: Variant 1 JAR 1 ***:
    Entering TestClass1.testMethod() packaged in JAR1.jar
    About to instantiate TestClass2 with the new operator
    About to call TestClass2.testMethod()
    Entering TestClass2.testMethod() packaged in JAR1.jar
    *** UC1: Variant 1 JAR 2 ***:
    Entering TestClass1.testMethod() packaged in JAR2.jar
    About to instantiate TestClass2 with the new operator
    About to call TestClass2.testMethod()
    Entering TestClass2.testMethod() packaged in JAR2.jar
    *** static UC2: Variant 2 JAR 1 ***:
    Exception in thread "main" java.lang.NoClassDefFoundError: TestClass1
            at UC2.runFromJarVariant2_static(UC2.java:56)
            at TestClassPathMain.main(TestClassPathMain.java:52)
    TestClassPathMain.java
    import java.lang.reflect.InvocationTargetException;
    import java.lang.reflect.Method;
    import java.net.MalformedURLException;
    import java.net.URL;
    import java.net.URLClassLoader;
    public class TestClassPathMain {
        public static void main(final String args[]) throws MalformedURLException, ClassNotFoundException, InstantiationException, SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException {
                // Commented out because I cannot catch the NoClassDefFoundError.
                // Why?
                try {
                    final TestClass1 testClass1 = new TestClass1();
                    System.out.println(
                        "\nThe class TestClass1 is of some unexplicable reason available." +
                        "\nFor the purpose of the test, it shouldn't have been!" +
                        "\nExiting");
                    System.exit(1);
                } catch (NoClassDefFoundError e) {
                    System.out.println("\nPositively confirmed that the class TestClass1 is not available:\n" + e);
                    System.out.println("\n\nREADY FOR THE TEST: ...");
                // Works fine
                System.out.println("\n*** Main: Variant 1 JAR 1 ***:");
                runFromJarVariant1("file:/W:/java/eclipse/workspaces/simped_test/CP1/JAR1.jar");
                System.out.println("\n*** Main: Variant 1 JAR 2 ***:");
                runFromJarVariant1("file:/W:/java/eclipse/workspaces/simped_test/CP2/JAR2.jar");
                // Works fine
                System.out.println("\n*** Main: Variant 2 JAR 1 ***:");
                runFromJarVariant1("file:/W:/java/eclipse/workspaces/simped_test/CP1/JAR1.jar");
                System.out.println("\n*** Main: Variant 2 JAR 2 ***:");
                runFromJarVariant1("file:/W:/java/eclipse/workspaces/simped_test/CP2/JAR2.jar");
                // Works fine
                final UC1 uc1 = new UC1();
                System.out.println("\n*** UC1: Variant 1 JAR 1 ***:");
                uc1.runFromJarVariant1("file:/W:/java/eclipse/workspaces/simped_test/CP1/JAR1.jar");
                System.out.println("\n*** UC1: Variant 1 JAR 2 ***:");
                uc1.runFromJarVariant1("file:/W:/java/eclipse/workspaces/simped_test/CP2/JAR2.jar");
                // Crashes
                System.out.println("\n*** static UC2: Variant 2 JAR 1 ***:");
                UC2.runFromJarVariant2_static("file:/W:/java/eclipse/workspaces/simped_test/CP1/JAR1.jar");
                System.out.println("\n*** static UC2: Variant 2 JAR 2 ***:");
                UC2.runFromJarVariant2_static("file:/W:/java/eclipse/workspaces/simped_test/CP2/JAR2.jar");
                // Crashes
                final UC2 uc2 = new UC2();
                System.out.println("\n*** UC2: Variant 2 JAR 1 ***:");
                uc2.runFromJarVariant2("file:/W:/java/eclipse/workspaces/simped_test/CP1/JAR1.jar");
                System.out.println("\n*** UC2: Variant 2 JAR 2 ***:");
                uc2.runFromJarVariant2("file:/W:/java/eclipse/workspaces/simped_test/CP2/JAR2.jar");
        private static void runFromJarVariant1(final String jarFileURL)
            throws MalformedURLException,
                   ClassNotFoundException,
                   InstantiationException,
                   IllegalArgumentException,
                   IllegalAccessException,
                   InvocationTargetException,
                   SecurityException,
                   NoSuchMethodException {
            final URL url = new URL(jarFileURL);
            final URLClassLoader cl =
                new URLClassLoader(new URL[]{url},
                                   Thread.currentThread().getContextClassLoader());
            final Class clazz = cl.loadClass("TestClass1");
            final Object testClass1 = clazz.newInstance();
            final Method testMethod1 = clazz.getMethod("testMethod", null);
            testMethod1.invoke(testClass1, null);
        private static void runFromJarVariant2(final String jarFileURL)
            throws MalformedURLException,
                   ClassNotFoundException,
                   InstantiationException,
                   IllegalArgumentException,
                   IllegalAccessException,
                   InvocationTargetException,
                   SecurityException,
                   NoSuchMethodException {
            final URL url = new URL(jarFileURL);
            final URLClassLoader cl =
                new URLClassLoader(new URL[]{url},
                                   Thread.currentThread().getContextClassLoader());
            final Class clazz = cl.loadClass("TestClass1");
            final TestClass1 testClass1 = new TestClass1();
            testClass1.testMethod();
    UC1.java
    import java.lang.reflect.InvocationTargetException;
    import java.lang.reflect.Method;
    import java.net.MalformedURLException;
    import java.net.URL;
    import java.net.URLClassLoader;
    public class UC1 {
        public void runFromJarVariant1(final String jarFileURL)
            throws MalformedURLException,
                   ClassNotFoundException,
                   InstantiationException,
                   IllegalArgumentException,
                   IllegalAccessException,
                   InvocationTargetException,
                   SecurityException,
                   NoSuchMethodException {
            final URL url = new URL(jarFileURL);
            final URLClassLoader cl =
                new URLClassLoader(new URL[]{url},
                                   Thread.currentThread().getContextClassLoader());
            final Class clazz = cl.loadClass("TestClass1");
            final Object testClass1 = clazz.newInstance();
            final Method testMethod1 = clazz.getMethod("testMethod", null);
            testMethod1.invoke(testClass1, null);
    UC2.java
    import java.lang.reflect.InvocationTargetException;
    import java.net.MalformedURLException;
    import java.net.URL;
    import java.net.URLClassLoader;
    public class UC2 {
        public void runFromJarVariant2(final String jarFileURL)
        throws MalformedURLException,
               ClassNotFoundException,
               InstantiationException,
               IllegalArgumentException,
               IllegalAccessException,
               InvocationTargetException,
               SecurityException,
               NoSuchMethodException {
            final URL url = new URL(jarFileURL);
            final URLClassLoader cl =
                new URLClassLoader(new URL[]{url},
                                   Thread.currentThread().getContextClassLoader());
            final Class clazz = cl.loadClass("TestClass1");
            final TestClass1 testClass1 = new TestClass1();
            testClass1.testMethod();
         * Identic to the "runFromJarVariant2" method,
         * except that it is static
        public static void runFromJarVariant2_static(final String jarFileURL)
        throws MalformedURLException,
               ClassNotFoundException,
               InstantiationException,
               IllegalArgumentException,
               IllegalAccessException,
               InvocationTargetException,
               SecurityException,
               NoSuchMethodException {
            final URL url = new URL(jarFileURL);
            final URLClassLoader cl =
                new URLClassLoader(new URL[]{url},
                                   Thread.currentThread().getContextClassLoader());
            final Class clazz = cl.loadClass("TestClass1");
            final TestClass1 testClass1 = new TestClass1();
            testClass1.testMethod();
    }

    2. i need to load the class to the same JVM (i.e. to
    the same environment) of the current running
    aplication, so that when the loaded class is run, it
    would be able to invoke methods on it!!!
    ClassLoader(s) do this. Try the URLClassLoader.
    (I was talking about relatively esoteric "security"
    issues when I mentioned the stuff about Class objects
    "scope".) You might use the URLClassLoader kind of
    like this.
    Pseudo-code follows:
    // setup the class loader
    URL[] urls = new URL[1];
    urls[0] = new URL("/path/to/dynamic/classes");
    URLClassLoader ucl = new URLClassLoader(urls);
    // load a class & use make an object with the default constructor
    Object tmp = ucl.loadClass("dynamic.class.name").newInstance();
    // Cast the object to a know interface so that you can use it.
    // This may be used to further determine which interface to cast
    // the class to. Or it may simply be the interface to which all
    // dynamic classes have to conform in your program.
    InterfaceImplementedByDynamicClass loadedObj =
        (InterfaceImplementedByDynamicClass)tmp;It's really not as hard as it sounds, just write a little test of
    this and you will see how it works.

  • Dynamic class load problem..

    Hello all,
    I am rather new to this concept of creating class loaders.
    I started on a simple test and landed into a problem right away. I have a Java class file stuffed away somewhere on m machine (at a location not on my CLASSPATH) . I just want to load that class dynamically. Here is my humble code :
    import java.io.*;
    public class DynamicClassLoadTest extends ClassLoader {
         String classFileName;
         String pathToClassFile;
         public static void main(String[] args) {
              try {
                   if(args.length != 2) {
                        System.out.println("Usage : java DynamicClassLoadTest <path to class file> <name of class file>");
                        System.exit(0);
                   System.out.println("MISSION: To dynamically load class " + args[1] + " from path : " + args[0]);
                   DynamicClassLoadTest dcl = new DynamicClassLoadTest();
                   Class cls = dcl.loadClass(args[1], args[0], true);
              catch(Exception e) {
                   System.out.println("Mission failed with error : " + e);
                   e.printStackTrace();
         public Class loadClass(String name, String path, boolean resolve)
              throws ClassNotFoundException
              this.pathToClassFile=path;
              this.classFileName= name;
              return (loadClass(name, resolve));
         public Class loadClass(String name, boolean resolve)
              throws ClassNotFoundException
              try {
                   File f = new File(pathToClassFile, name + ".class");
                   if(!f.exists())
                        throw new ClassNotFoundException("Specified class not found");
                   FileInputStream fis = new FileInputStream(f);
                   long fileSize = f.length();
                   System.out.println("Size of class file = " + fileSize);
                   byte[] classBytes = new byte[(int) fileSize];
                   int r = fis.read(classBytes);
                   System.out.println("Bytes read is " + r + " and file size is " + fileSize + " and byte array length is " + classBytes.length);
                   Class c = defineClass(name, classBytes, 0, classBytes.length);
                   System.out.println("CLASS created..");
                   return c;
              catch(Exception e) {
                   throw new ClassNotFoundException(e.getMessage());
    When I execute as :
    java DynamicClassLoadTest /Users/user1 JustTest
    the below is printed on execution :
    MISSION: To dynamically load class JustTest from path : /Users/user1
    Size of class file = 421
    Bytes read is 421 and file size is 421 and byte array length is 421
    Exception in thread "main" java.lang.NoClassDefFoundError: java/lang/Object
    at java.lang.ClassLoader.defineClass0(Native Method)
    at java.lang.ClassLoader.defineClass(ClassLoader.java:502)
    at java.lang.ClassLoader.defineClass(ClassLoader.java:431)
    at DynamicClassLoadTest.loadClass(DynamicClassLoadTest.java:56)
    at DynamicClassLoadTest.loadClass(DynamicClassLoadTest.java:33)
    at DynamicClassLoadTest.main(DynamicClassLoadTest.java:18)
    The class file has apparently been read fine - then why is this java/lang/object reference ?
    Any tips would be of huge help.
    Thanks.

    An extension to this.
    What should I do when I have to load a jar dynamically ? I manage to load the main class of the jar successfully. But what about classes in the jar which are invoked by this class. Say we have case as below :
    JustAJar.jar contains :
    sh-2.05a$ jar tvf JustAJar.jar
    0 Fri May 23 14:41:14 PDT 2003 META-INF/
    70 Fri May 23 14:41:14 PDT 2003 META-INF/MANIFEST.MF
    567 Fri May 23 14:40:52 PDT 2003 InvokeTheNext.class
    475 Fri May 23 14:40:52 PDT 2003 InvokeMe.class
    Now, InvokeMe is the class I instantiate :
    public class InvokeMe {
    public static void main(String[] args) {
    System.out.println("Welcome to InvokeMe");
    InvokeTheNext itn = new InvokeTheNext("InvokeMe");
    InvokeTheNext is :
    public class InvokeTheNext {
    public InvokeTheNext(String str) {
    System.out.println("Welcome to InvokeTheNext");
    System.out.println("Recd ur msg " + str);
    Now I manage to define and resolve the class InvokeMe, but when the class is invoked, the foll error is thrown :
    Resolved class with name InvokeMe successfully
    Welcome to InvokeMe
    Mission failed with error : java.lang.reflect.InvocationTargetException
    java.lang.reflect.InvocationTargetException
         at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
         at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
         at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
         at java.lang.reflect.Method.invoke(Method.java:324)
         at InvokeForClassLoad.main(InvokeForClassLoad.java:46)
    Caused by: java.lang.NoClassDefFoundError: InvokeTheNext
         at InvokeMe.main(InvokeMe.java:4)
    I tried loading the entire jar file into the CLASSPATH dynamically (using System.setProperty) but that doesnt help. Any inputs please ?
    Thanks.

  • Class Loader Issues

    I am dynamically creating .class files on the fly in my application. Often I need to rebuild the same class (including client classes) multiple times. The problem is that the system ClassLoader keeps the 1st .class file in memory and will not return to the disk to retrieve the new version after the class file(s) have changed.
    Do I need to write a new Classloader and substitute it for the main systems class loader? Is there a better way to instantiate the class other than Class.forName( blah ) that will solve this problem?
    Thanks,
    -Jeff Harman

    Like we told you. If the code for a class changes, Java will not automatically notice and load the new version, until you start up the JVM again. If you do not want to re-start the VM, you can create a new ClassLoader (CL), and use it to load the new code for the class.
    Now, the problem is, the second CL may think it has to reload many of other classes, since it has no record of loading them itself. You will end up with duplicates of many classes.
    If that doesn't suit you, there is not much alternatives.
    You could rename the new version of the class, which would mean you'd have to manually track down all the old versions and upgrade them ( by using the new Ctor). You'd then have to update all the references to make them point to the new object. You can make that particular job easier by making both classes (old and new) extend a common base class, or implements the same interface, and use the interface reference (i.e program to an interface).
    Another less-than-perfect possibility would be to use serialization where you serialise version-marked objects and reconstitute them with new code...
    Good luck.

  • InitialContext Class Loader

    Hi all,
    We are experiencing a strange behaviour of the Application Class Loader. Our main issue is that if we deploy 2 applications using our code, the first application is okay, and the second application fails its loading. During the loading, we instantiate a customized InitialContextFactory (two times at all: one time per application). As a result, we have a ClassCastException in our customized InitialContext. Above a more detailed explanation of what happen. To sum up, we think that our InitialContextFactory is loaded by a master class loader, only one time for the 2 applications, and that the second application reaches the customized InitialContextFactory instantiated for the first application, so the classes loaded for the second application are not compatible.
    Details:
    - Each Application create a new InitialContext with the parameter "java.naming.factory.initial" equals to "com.test.CustomInitialContextFactory".
    - In the class com.test.CustomInitialContextFactory we access to other code from our application, which are passed to the context factory by the environment hashtable. In the method public javax.naming.Context getInitialContext(java.util.Hashtable env), we get some parameters from the env parameter like that: CustomObject o = (CustomObject)env.get("com.test.customObject");
    When the first application launches, it works very well.
    When the second application launches, it fails with a ClassCastException on the class com.test.CustomObject. We think that the class com.test.CustomObject is not loaded by the good class loader so it throws a ClassCastException.
    Thank you for your help

    We have found how the JNDI layer builds the specified context factory:
              ClassLoader cl = (ClassLoader) AccessController.doPrivileged(
                   new PrivilegedAction() {
                   public Object run() {
                        return Thread.currentThread().getContextClassLoader();
    But OC4J has specific Thread ClassLoader: this is the cause of all our problem. So there is a solution: create a specific context factory which calls the good class loader to load the context factory.
    Bye

  • RMI Dynamic Class Loading

    Hello,
    I have a standalone Java Client which is connecting to an RMI based svr component on WLS 6.0sp1. However, before connecting to the RMI Svr, I am trying to boot strap couple of other CLASS files from the App Svr. using the RMIClassLoader. Now here's the problem...
    I have placed my classes( one which I want to download and instantiate before I start making conventional calls to RMI Svr remote methods) in the folder WL_HOME/config/examples/rmi/*.class
    which is the code_base url I use. However, the error I get when trying to download the classs using RMIClass loader is:
    No Security Manager: RMI Class Loader disabled"...
    due to which I can not even get connected to my remote object after that. Can somebody please tell me how can I set whatever option it is so that I can get this thing working.
    I tried using the "Grant all" security policy too on the client side & server side in vain.
    Any help is truly appreciated. Thanks a lot!
    cl I am trying to

    I'll try having a crack at this, see inline comments
    Chirag Shah wrote:
    Hello,
    I have a standalone Java Client which is connecting to an RMI based svr component on WLS 6.0sp1. However, before connecting to the RMI Svr, I am trying to boot strap couple of other CLASS files from the App Svr. using the RMIClassLoader. Now here's the problem...
    I have placed my classes( one which I want to download and instantiate before I start making conventional calls to RMI Svr remote methods) in the folder WL_HOME/config/examples/rmi/*.class
    which is the code_base url I use. However, the error I get when trying to download the classs using RMIClass loader is:I'll assume that you're using a proper URL (file://) to instanciate your ClassLoader.
    >
    No Security Manager: RMI Class Loader disabled"...
    Does your client explicitly set a SecurityManager using the following command?
    if (System.getSecurityManager() == null) {
    System.setSecurityManager(new java.rmi.RMISecurityManager());
    Also,I believe that it should only be your client changing its policy file (for the network classload).
    >
    due to which I can not even get connected to my remote object after that. Can somebody please tell me how can I set whatever option it is so that I can get this thing working.
    I tried using the "Grant all" security policy too on the client side & server side in vain.
    Any help is truly appreciated. Thanks a lot!
    cl I am trying toHope it helps,
    Stephane Vaucher
    CIRANO
    Research Professional

  • Design patterns for Dynamic Class Loading

    Hi,
    I have to develop a program for uni that dynamically loads classes based on names in a text file. All the classes subclass an abstract class with a constructor that takes one argument. This means I can't use the Class.forName(className).newInstance() method of class loading. I have researched some design patterns I could use and have come up with the following 3:
    Factory pattern; "Robocode" pattern (not it's real name, but Robocode uses it); and, the "one I made up myself" pattern.
    The robocode pattern instantiates a class using the default no-argument constructor then immediately sets all properties that shoud have been provided in the constructor:
    Object o = Class.forName(myClass).newInstance();
    o.setProperty(property);Personally I think this is ugly and a cheap fix instead of doing it properly.
    My own pattern finds the constructor that takes the arguments I need then calls it to create the object:
    Class c = Class.forName(myClass);
    Constructor cons = c.getConstructor(new Class[]{Class.forName("java.lang.String")});
    Object o = cons.newInstance(new Object[]{"hello"});What's the best to use? Are there any other patterns I should consider?

    My own pattern finds the constructor that takes the
    arguments I need then calls it to create the object:
    Class c = Class.forName(myClass);
    Constructor cons = c.getConstructor(new
    Class[]{Class.forName("java.lang.String")});
    Object o = cons.newInstance(new Object[]{"hello"});
    I have followed this basic 'pattern' several times though I would use
    Constructor cons = c.getConstructor(new Class[]{String.class});
    It works great.

  • A question on class loading

    Say, I hava a class A which has inner classes, are those inner classes loaded when I load class A into JVM? Thanks

    Hmm ... depends on the way you use the inner classes.
    For example if there's a way to gather instances of
    "A.aa" by calling a (factory) method on class "A",
    you'd only have to get an instance of "A" via the
    URLClassLoader. The ClassLoader of "A" would do the
    job of loading "A.aa" in this case. If you want to
    instantiate inner classes directly through e.g. a
    call to Class.newInstance(), you'd have to do as you
    wrote. I guess.My situation is that there is one instance of each of those inner classes. And those instances are created when they are declared in "A" as member variables.

  • New to dynamic class loading - could you help me?

    Hi all!
    Thanks so much for taking a minute to read my post.
    I am a rookie at java and programming.
    I have a program that needs to load a class (or java file) dynamically during runtime. (At least I think that is what it needs to do.)
    I want the user of the program to be able to specify a .java or a .class file either somewhere on the local disk or network, but not necessarily in the same location as the program itself. Once that file is selected, I would like the program to be able to use that file as if it were a .class file created in the working directory when the program was compiled and created.
    I have read a lot of the forums, and I think I need to write my own class loader. I tried creating a class loader, and the code is shown below. (I borrowed this code from some of the other forums I've read.)
    Here is my problem.
    1. Should I be trying to extend the ClassLoader class? Am I on the right track?
    2. If I am on the right track, should I require the user of my program to select a previously compiled ".class" file? Or should I ask them to indicate a ".java" file, and try to compile the java file with the program?
    3. I'm sure that if the above two questions are answered, the solution to this problem will become obvious. But for clarity, I should mention that with the current code (below), I keep getting a java.lang.NoClassDefFoundError inside the class FileClassLoader at the line:
    c = defineClass (classname, buff, 0, buff.length); Obviously, I am not providing the right information to this FileClassLoader in order to create the class. Can you help me out?
    Thank you in advance!
    I really appreciate it!
    Best Regards,
    Julia
    class SampleClass
      public void sampleMethod()
       final JFileChooser fc = new JFileChooser();
       int returnVal = fc.showOpenDialog(optionPane);
       if (returnVal == JFileChooser.APPROVE_OPTION) {
         File file = fc.getSelectedFile();
         try
            FileClassLoader loader = new FileClassLoader(file);
               Class cl = loader.loadClass(file.getName(),false);
            }catch ( ClassNotFoundException e ) {
           System.out.println("ClassNotFoundException");
         }catch (IllegalAccessException e) {
           System.out.println("IllegalAccess");      
         }catch( InstantiationException e) {
           System.out.println("Can't Instantiate That");
    class FileClassLoader extends ClassLoader
         private File file;
         public FileClassLoader (File thisFile)
              this.file = thisFile;
         protected synchronized Class loadClass(String s, boolean bool) throws ClassNotFoundException
              Class c = null;
              try {
                   int size = (int)file.length();
                   byte buff[] = new byte[size];
                   FileInputStream fis = new FileInputStream(file);
                   DataInputStream dis = new DataInputStream (fis);
                   dis.readFully (buff);
                   dis.close();
                   String classname = null;
                   String filename = file.getName();
                   int i = filename.lastIndexOf('.');
                   if(i>0 && i<filename.length()-1)
                        classname = filename.substring(0,i);
                   c = defineClass (classname, buff, 0, buff.length);
                   resolveClass (c);
              } catch (java.io.IOException e) {
                   e.printStackTrace();
              return c;
    }

    Hi!
    If you really need to do that, you can give a look at my previous post at:
    http://forum.java.sun.com/thread.jsp?forum=4&thread=285674
    You can play with the code to suit your needs.
    Hope this helps.

  • Help Needed on a similar but not same class loader problem

    Hi,
    Please help...
    There is a ClassLoader called MyLoader that overrides default findClass() method to decrypt already encrypted class files available in a separate jar file.
    MyClass also contains a public static method launchMe() method that starts off with a call similar to loadClass("ApplicationMainClass");
    The MyLoader class is also encrypted
    I modified the default launcher (c) code to:
    First find the encrypted MyLoader file then decrypt it and create a byte array.
    The byte array, along with the system class loader and other required arguments, is passed to DefineClass native method (defined in jvm.dll)
    Note: The system class loader class has been instantiated using static method ClassLoader.getSystemClassLoader() through Java's invocation API.
    The DefineClass succeeds and I'm able to instantiate MyLoader and later call launchMe() to start application.
    Now i come to the problem:
    I'm not able to use any class other that those in rt.jar (i.e.standard classes) in MyLoader class. I end up with a runtime error ClassDefNotFoundError while trying to load any third party jar.
    The classes i need are present in class path and also in the local jre's ext that i use to launch my app.
    Although i can avoid using third party jar in MyLoader but if there is any way...
    Piyush

    make sure that third party jar resides in your library.....
    or else put rt.jar and external jars under same folder
    this is matter of path.... no else than this.......
    cheers
    Rajesh42

  • How to load a class dynamically in the current/system class loader

    I need to dynamically load a new jdbc driver jar to the current/system class loader... Please note that creating a new classloader will not help since the DriverManager refers to the systemclassloader itself.
    Restarting the application by appending the jar to its classpath will solve the problem but I want to avoid doing this.

    Did you then create a ClassLoader to load the JDBC
    driver and then install it into the system as
    directed by the JDBC specification (ie
    Class.forName(someClassName))?
    And then try to use it from a class loaded fromsome
    other ClassLoader (i.e. the system class loader)?
    If you did not try this please explain why not.O.K. I just looked at the source to
    java.sql.DriverManager. I did not know what I was
    talking about, as what I suggested above will not
    work.
    This is my new Idea:
    Create a URLClassLoader to load the JDBC driver also
    in this ClassLoader you need to place a helper class
    that does the following:
    public class Helper {
    public Driver getJDBCDriver(String driverClassName,
    String url) {
    try {
    Class.forName(driverClassName);
    Driver d = DriverManager.getDriver(url);
    return d;
    catch(Exception ex) {
    ex.printStackTrace();
    return null;
    }Now create an instance of the Helper class in the new
    ClassLoader, and call its getJDBCDriver method to get
    an instance of the driver (you will probably have to
    create an interface in the root class loader that the
    Helper implements so that you can easily call it).
    Now from the root classloader you can make calls
    directly to the returned Driver and bypass the
    DriverManager and its restrictions on cross
    ClassLoader access.
    The only catch here is that you would have to call to
    the returned Driver directly and not use the Driver
    Manager.This sounds like will work but I did not want to load DriverManager in a new classloader.. I did a hack
    I unzip the jar dynamically in a previously known location (which I included in my classpath when launching the app). The classLoader finds the class now though it did not exist when the app was launched !
    A hack of-course but works eh ..

  • Error building project using kXML2 - "Class loading error: Wrong name"

    Hi,
    I'm testing the XML-Parser KXML2 and downloaded the latest package, but the minimal version (kxml2-min.zip). I put this file into the directory "%j2mewtk%\apps\KxmlTest\lib" and wrote the lines
    import org.kxml2.io.*;
    import org.xmlpull.v1.*;
    When I try to build the project with the Wireless Toolkit (v1.04) it spits out the following error:
    Error preverifying class kxml2.io.KXmlParser
    Class loading error: Wrong name
    com.sun.kvem.ktools.ExecutionException: Preverifier returned 1
    Build failed
    I also tried the full package "kxml2.zip" but the same error occurs.
    How can I get rid of this? Thanks in advance!

    Okay, finally worked it out (hopefully). I unpacked the archive to a directory (say "%J2MEWTK%\apps\KxmlTest\tmpclasses") and then preverified them "manually":
    %J2SDK%\bin\preverify.exe -classpath "%J2MEWTK%\apps\KxmlTest\tmpclasses";"%J2MEWTK%\lib\midpapi.zip" org.kxml2.io.KXmlParser
    %J2SDK%\bin\preverify.exe -classpath "%J2MEWTK%\apps\KxmlTest\tmpclasses";"%J2MEWTK%\lib\midpapi.zip" org.xmlpull.v1.XmlPullParser
    %J2SDK%\bin\preverify.exe -classpath "%J2MEWTK%\apps\KxmlTest\tmpclasses";"%J2MEWTK%\lib\midpapi.zip" org.xmlpull.v1.XmlPullParserException
    Then I packed them again to a jar-file:
    %J2SDK%\bin\jar.exe -cvf kxml2-min.jar %J2MEWTK%\apps\KxmlTest\tmpclasses\output\.
    That was all!

  • Performance issues with class loader on Windows server

    We are observing some performance issues in our application. We are Using weblogic 11g with Java6 on a windows 2003 server
    The thread dumps indicate many threads are waiting in queue for the native file methods:
    "[ACTIVE] ExecuteThread: '106' for queue: 'weblogic.kernel.Default (self-tuning)'" RUNNABLE
         java.io.WinNTFileSystem.getBooleanAttributes(Native Method)
         java.io.File.exists(Unknown Source)
         weblogic.utils.classloaders.ClasspathClassFinder.getFileSource(ClasspathClassFinder.java:398)
         weblogic.utils.classloaders.ClasspathClassFinder.getSourcesInternal(ClasspathClassFinder.java:347)
         weblogic.utils.classloaders.ClasspathClassFinder.getSource(ClasspathClassFinder.java:316)
         weblogic.application.io.ManifestFinder.getSource(ManifestFinder.java:75)
         weblogic.utils.classloaders.MultiClassFinder.getSource(MultiClassFinder.java:67)
         weblogic.application.utils.CompositeWebAppFinder.getSource(CompositeWebAppFinder.java:71)
         weblogic.utils.classloaders.MultiClassFinder.getSource(MultiClassFinder.java:67)
         weblogic.utils.classloaders.MultiClassFinder.getSource(MultiClassFinder.java:67)
         weblogic.utils.classloaders.CodeGenClassFinder.getSource(CodeGenClassFinder.java:33)
         weblogic.utils.classloaders.GenericClassLoader.findResource(GenericClassLoader.java:210)
         weblogic.utils.classloaders.GenericClassLoader.getResourceInternal(GenericClassLoader.java:160)
         weblogic.utils.classloaders.GenericClassLoader.getResource(GenericClassLoader.java:182)
         java.lang.ClassLoader.getResourceAsStream(Unknown Source)
         javax.xml.parsers.SecuritySupport$4.run(Unknown Source)
         java.security.AccessController.doPrivileged(Native Method)
         javax.xml.parsers.SecuritySupport.getResourceAsStream(Unknown Source)
         javax.xml.parsers.FactoryFinder.findJarServiceProvider(Unknown Source)
         javax.xml.parsers.FactoryFinder.find(Unknown Source)
         javax.xml.parsers.DocumentBuilderFactory.newInstance(Unknown Source)
         org.ajax4jsf.context.ResponseWriterContentHandler.<init>(ResponseWriterContentHandler.java:48)
         org.ajax4jsf.context.ViewResources$HeadResponseWriter.<init>(ViewResources.java:259)
         org.ajax4jsf.context.ViewResources.processHeadResources(ViewResources.java:445)
         org.ajax4jsf.application.AjaxViewHandler.renderView(AjaxViewHandler.java:193)
         org.apache.myfaces.lifecycle.RenderResponseExecutor.execute(RenderResponseExecutor.java:41)
         org.apache.myfaces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:140)
    On googling this seems to be an issue with java file handling on windows servers and I couldn't find a solution yet. Any recommendation or pointer is appreciated

    Hi shubhu,
    I just analyzed your partial Thread Dump data, the problem is that the ajax4jsf framework ResponseWriterContentHandler triggers internally a new instance of the DocumentBuilderFactory; every time; triggering heavy IO contention because of Class loader / JAR file search operations.
    Too many of these IO operations under heavy load will create excessive contention and severe performance degradation; regardless of the OS you are running your JVM on.
    Please review the link below and see if this is related to your problem.. This is a known issue in JBOSS JIRA when using RichFaces / ajaxJSF.
    https://issues.jboss.org/browse/JBPAPP-6166
    Regards,
    P-H
    http://javaeesupportpatterns.blogspot.com/

  • How can I make server use single class loader for several applications

    I have several web/ejb applications. These applications use some common libraries and should share instances of classes from those libraries.
    But applications are being deployed independently thus packaging all them to EAR is not acceptable.
    I suppose the problem is that each application uses separate class loader.
    How can I make AS use single class loader for a set of applications?
    Different applications depend on different libraries so I need a way that will not share library for all applications on the domain but only for some exact applications.
    When I placed common jar to *%domain%/lib* - all works. But that jar is shared between all applications on the domain.
    When I tried to place common jar to *%domain%/lib/applibs* and specified --libraries* attribute on deploying I got exception
    java.lang.ClassCastException: a.FirstDao cannot be cast to a.FirstDaoHere http://download.oracle.com/docs/cd/E19879-01/820-4336/6nfqd2b1t/index.html I read:
    If multiple applications or modules refer to the same libraries, classes in those libraries are automatically shared.
    This can reduce the memory footprint and allow sharing of static information.Does it mean that classes should be able to be casted ?

    You didn't specify which version of the application server you are using, but the config is similar as long as you know what to look for. Basically, you need to change the classloader delegation. Here's how it is done in 8.2
    http://download.oracle.com/docs/cd/E19830-01/819-4721/beagb/index.html

  • How can I get a dynamic list of Classes Loaded

    I assume this may need to use some sort of reflection. Does
    anyone have code or ideas where I can:
    a) I can get a list of all Classes loaded and their
    properties. This would probably be all instances of Class
    b) A list of all
    global instance variables. (This may not even be possible. I
    know it can be done in other languages)
    I assume this may need to use some sort of reflection.
    Thank you

    Adobe Newsbot hopes that the following resources helps you.
    NewsBot is experimental and any feedback (reply to this post) on
    its utility will be appreciated:
    mx.controls.List (Flex 3):
    If the data is incorrect, you can call the preventDefault()
    method to stop Flex from passing the new data back to the list
    control and from closing the
    Link:
    http://livedocs.adobe.com/flex/3/langref/mx/controls/List.html
    Displaying icons in a Flex List control at Flex Examples:
    http://blog.flexexamples.com/2007/08/17/displaying-icons-in-a-flex-list-control/
    --> <mx:Application xmlns:mx=&quot;
    http://www.adobe.com/2006/mxml&quot;
    Link:
    http://blog.flexexamples.com/2007/08/17/displaying-icons-in-a-flex-list-control/
    Populate the list -- Flex 2.01:
    You populate a list-based form control with the
    <mx:dataProvider> child tag. The <mx:dataProvider> tag
    lets you specify list items in several ways.
    Link:
    http://livedocs.adobe.com/flex/201/html/tutorial_controls_019_4.html
    Smooth Scroll for Horizontal List - Flex India Community |
    Google:
    I have created image gallery with Horizontal List[Flex 2.0].
    Just as below ref site. My Problem is i need a smooth scroll for
    Horizontal List. where images
    Link:
    http://groups.google.com/group/flex_india/browse_thread/thread/a12441143b98d32c?hide_quote s=no
    Creating a List control -- Flex 2.01:
    The following example code adds a handler for a change event
    to the List control. Flex broadcasts a mx.ListEvent.CHANGE event
    when the value of the control
    Link:
    http://livedocs.adobe.com/flex/201/html/dpcontrols_062_03.html
    Disclaimer: This response is generated automatically by the
    Adobe NewsBot based on Adobe
    Community
    Engine.

Maybe you are looking for

  • My C665 S5046 no longer recognizes the hard drive

    I booted up my toshiba C665 S5046 and it goes to a screen stating I need to use a boot disk?  Any idea what happened or what can I do as a work around?  Does this mean the hard drive is bad?

  • Invalid Content Type Error in Receiver SOAP Adapter

    Hello Experts, Is there a solution for this problem? I am getting the following error in one of my receiver SOAP adapters: com.sap.aii.af.ra.ms.api.DeliveryException: XIAdapterFramework:...:com.sap.aii.af.ra.ms.api.DeliveryException: invalid content

  • ContentPath not working in a loop for a Loader component

    i'm trying to load pics into a loader in my movieclip, i'm looping through about 20 items, to be placed in a movieclips dynamically attached... this does not work... mcContainer['node'+nCount].pic.contentPath=myimagepath; this does work... mcContaine

  • REgistering on BT WiFi with non BTinternet email a...

    I have BT Infinity and so should be able to use the BT WiFi app when out and about. My login email is not a BTinternet address. I wasn't using it and I believe that it has been discontinued. How do I register with the username I have? I have tried th

  • Clone Stamp malfunctioning

    After I choose a source area and release the alt key, the image duplicates and then moves independently over top of the original as though it is being dragged around by the cursor.  I have had Elements 12 for about 2 weeks and tonight it began doing