Class.forName problem

Hi,
I'm using "Java Invocation API" to load a class and call a generic method of it,
but the "forName" call fails with error:
     Exception in thread "Thread-4" java.lang.ClassNotFoundException: HelloWorld
          at java.lang.Class.forName0(Native Method)
          at java.lang.Class.forName(Class.java:217)
here is my (pseudo) code:
// connect to my class "HelloWorld"
myClass = (*envP)->FindClass(env, "HelloWorld")
// connect to class "Java/lang/Class"
classClass = (*env)->FindClass(env, "java/lang/Class")
// get the id of Class.forName method
forNameID = (*env)->GetStaticMethodID(env, classClass, "forName", "(Ljava/lang/String;)Ljava/lang/Class;")
// j name of HelloWorld
jClassName = (*env)->NewStringUTF(env, "HelloWorld")
// call forName -> fails
jClassObject = (*env)->CallStaticObjectMethod(env, classClass, forNameID, jClassName)
     -----> Exception in thread "Thread-4" java.lang.ClassNotFoundException: HelloWorld
          at java.lang.Class.forName0(Native Method)
          at java.lang.Class.forName(Class.java:217)
Sustem: MacOSX 10.2.8
Java Version: 1.4.1
$CLASSPATH env var: /System/Library/Frameworks/JavaVM.framework/Versions/1.4.1/Classes
Can somebody help me or point me to some useful URL about this?
Thanks

Here is a simple app that demonstrates my problem. I compiled and ran it on MacOSX but I have the same problem on windows. Copy the following code in a file named "javatest.c", cd to that directory and compile it with commad:
gcc -o javatest javatest.c -framework JavaVMthen run it with:
./javatestCode:
#include <JavaVM/jni.h>
//===========================================================================================
static void print_exception(JNIEnv *envP)
     // output the exception
     if (envP && ((*envP)->ExceptionOccurred(envP) != NULL))
     {     (*envP)->ExceptionDescribe(envP);
          (*envP)->ExceptionClear(envP);
//===========================================================================================
int main()
JavaVMInitArgs     vm_args;
JavaVM               *jvm;
JavaVMOption        options[5];
char               *classPathEnv;
char               *classPathString;
jint               res;
JNIEnv                *envP = NULL;
jclass               jlcClass;
jmethodID          forNameID;
jstring               jClassName;
jobject               jClassObject;
     vm_args.version = JNI_VERSION_1_2;
     // options
     vm_args.nOptions = 5;
     options[0].optionString = "-verbose:class" ;
     options[1].optionString = "-verbose:jni" ;
     options[2].optionString = "-verbose:gc" ;
     classPathEnv = (char *)getenv( "CLASSPATH" );
     if (!(classPathString = (char*)malloc(strlen( "-Djava.class.path=" ) + strlen(classPathEnv) + 1)))
printf("malloc failed\n");
          exit(1);
     sprintf(classPathString, "%s%s" ,"-Djava.class.path=" , classPathEnv);
     options[3].optionString = classPathString;
     options[4].optionString = "vfprintf" ;
     options[4].extraInfo = vfprintf;
     vm_args.options = options;
     vm_args.ignoreUnrecognized = JNI_FALSE;
     // Load the jvm
     res = JNI_CreateJavaVM(&jvm, (void**)&envP, &vm_args);
     if (res != JNI_OK)
     {     printf("CreateJavaVM failed\n");
          exit(1);
     // find the class "java/lang/Class"
     if (!(jlcClass = (*envP)->FindClass(envP, "java/lang/Class")))
     {     printf("FindClass java/lang/Class failed\n");
          print_exception(envP);
          exit(1);
     // find the method ID of Class.forName
     if (!(forNameID = (*envP)->GetStaticMethodID(envP, jlcClass, "forName", "(Ljava/lang/String;)Ljava/lang/Class;")))
     {     printf("GetStaticMethodID forName failed\n");
          print_exception(envP);
          exit(1);
     // make a java string of my "HelloWorld" class
     if (!(jClassName = (*envP)->NewStringUTF(envP, "HelloWorld")))
     {     printf("NewStringUTF failed\n");
          print_exception(envP);
          exit(1);
     // call method Class.forName
     if (!(jClassObject = (*envP)->CallStaticObjectMethod(envP, jlcClass, forNameID, jClassName)))
     {     printf("CallStaticObjectMethod of forName failed\n");
          print_exception(envP);
          exit(1);
     // fail with:
     // java.lang.ClassNotFoundException: HelloWorld
     //        at java.lang.Class.forName0(Native Method)
     //        at java.lang.Class.forName(Class.java:115)
return 0;
}HelloWorld java code (compiled in a .class file located in $CLASSPATH folder):
public class HelloWorld
     public static void main (String args[]) throws Exception
          System.out.println ("HelloWorld");
}Someone can help me about this?

Similar Messages

  • Class.forname("").newInstance();   =   Problem!!  ;)

    I am distributing the application I am developping as a Jar file...
    In my application, there is a tool which interacts with a Database..
    As there is more than 1 existing database, and that they all require different drivers, I do not want to have to put every driver into my jar file, since it makes the file too big... I'd like to make it possible to download the drivers separatly, as another jar file... Although when I do that, I am not able to create a new instance of the driver...
    Here's what I have:
    Class.forName("org.gjt.mm.mysql.Driver").newInstance();
    This works fine when the driver has been included in the same jar file as my program.. How could I get it to work if the driver is in a separate Jar file, in the same folder as the jar file of my own application?

    I am distributing the application I am developping as
    a Jar file...
    In my application, there is a tool which interacts
    with a Database..
    As there is more than 1 existing database, and that
    they all require different drivers, I do not want to
    have to put every driver into my jar file, since it
    makes the file too big... I'd like to make it
    possible to download the drivers separatly, as another
    jar file... Although when I do that, I am not able to
    create a new instance of the driver...
    Here's what I have:
    Class.forName("org.gjt.mm.mysql.Driver").newInstance();
    This works fine when the driver has been included in
    the same jar file as my program.. How could I get it
    to work if the driver is in a separate Jar file, in
    the same folder as the jar file of my own application?I think the problem may be the classpath since it has to include the jar name specifically to find the classes in them. Perhaps you can set a new classpath with the System.setProperties() function so that the Class.forName() will work. I haven't tried that so I don't know if it will work.

  • Problems with Class.forName("com.sun.sql.jdbc.db2.DB2Driver")

    In sun java studio enterprise 8
    I'm able to connect to my local DB2 sample database by creating a database schema.
    But when I try to execute a java class (main) using
    Class.forName("com.sun.sql.jdbc.db2.DB2Driver"). It returns a not found condition.
    what am I doing wrong? do I have to point the classpath to some directory?

    try to add jar containing driver to
    Your project -> Properties -> Libraries -> Run list.

  • Class visibility problems in deployed OC4J application

    I have an entity, autogenerated from a database table by JDeveloper, which has the form:
    Entity.java:
    package a.b.c;
    import ...
    @Entity
    @NamedQuery( ... )
    @Table( ... )
    public class Entity implements Serializable {
        @Column( ... )
        : etc.
    }Then I have a stateless session bean, also autogenerated by JDeveloper, which has the form:
    SessionEJBBean.java:
    package a.b.c;
    import ...
    @Stateless(name="SessionEJB")
    public class SessionEJBBean implements SessionEJB {
        @PersistenceContext(unitName="Simple")
        private EntityManager em;
        public List<Entity> queryFindAll() {
            return em.createNamedQuery( ... ).getResultList();
        : etc.
    }Then I have my client (again, largely autogenerated):
    SessionEJBClient.java:
    package a.b.c;
    import ...
    public class SessionEJBClient {
        public static void main(String [] args) {
            try {
                final Context context = getInitialContext();
                SessionEJB sessionEJB = (SessionEJB)context.lookup("SessionEJB");
                List<Entity> entities = sessionEJB.queryFindAll();
            } catch (Exception ex) {
                ex.printStackTrace();
        private static Context getInitialContext() throws NamingException {
         : etc.
    }The above code works fine, however I now want to experiment with the oracle.toplink.essentials.tools.sessionconfiguration.SessionCustomizer interface. To this end, I create a bare-bones customizer class:
    Customizer.java:
    package a.b.c;
    import ...
    public class Customizer implements SessionCustomizer {
        public Customizer() {
        public void customize(Session session) {
    }and make corresponding updates to the persistence.xml file:
    persistence.xml:
    <?xml version="1.0" encoding="windows-1252" ?>
    <persistence
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
      http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"
      version="1.0" xmlns="http://java.sun.com/xml/ns/persistence">
      <persistence-unit name="Simple">
        <properties>
          <property name="toplink.session.customizer" value="a.b.c.Customizer"/>
        </properties>
      </persistence-unit>
    </persistence>Now, when I redeploy and attempt to run my client application, I'm told that the customizer class cannot be found:
    11-Jun-2007 16:32:17 oracle.j2ee.rmi.RMIMessages
    EXCEPTION_ORIGINATES_FROM_THE_REMOTE_SERVER
    WARNING: Exception returned by remote server: {0}
    javax.ejb.EJBException: Exception [TOPLINK-28006]
    (Oracle TopLink Essentials - 2006.8 (Build 060829)):
    oracle.toplink.essentials.exceptions.EntityManagerSetupException
    Exception Description: ClassNotFound: [a.b.c.Customizer]
    specified in [toplink.session.customizer] property.
    Internal Exception: oracle.classloader.util.AnnotatedClassNotFoundException:
           Missing class: com.logicacmg.security.Customizer
         Dependent class: oracle.toplink.essentials.internal.security.PrivilegedAccessHelper
                  Loader: oracle.persistence:1.0
             Code-Source: /usr/oc4j/toplink/jlib/toplink-essentials.jar
           Configuration: <code-source> in /usr/oc4j/j2ee/home/config/server.xml
    This load was initiated at oracle.persistence:1.0 using the Class.forName() method.
    The missing class is available from the following locations:
         1. Code-Source: /usr/oc4j/j2ee/home/applications/SimpleApp/SimpleApp.jar
    (from <ejb> in /usr/oc4j/j2ee/home/applications/SimpleApp)
            This code-source is available in loader SimpleApp.root:0.0.0.
    This is the current thread's context loader, and it appears that Class.forName()
    was used to load the dependent class. If a loader was not explicitly passed to
    Class.forName(), try passing the result of calling
    Thread.currentThread().getContextClassLoader()So, my question is: what is the correct way for me to configure the system so that my Customizer class is picked up?
    Apologies if this is obvious - I'm still rather new to working in this area (so if anything else I've written doesn't make sense - please don't be afraid to point it out!).
    Regards,
    Alistair.

    Hi, you all seem highly intelligent so I'll give this a shot.
    We're having a similar problem, but TopLink is not involved. Axis2 is, but in our case, the Axis2 application runs fine, it's the other applications that fail.
    We have three applications, Login, Candle, and Webservices (the one with Axis2). When we first start up the applications, they all instantiate fine. We can run Login pages and Candle pages fine. We can also run non-Axis2 Webservices servlets without breaking Login and Candle. But when we run a webservices servlet that uses Axis2, something happens that causes all future Login and Candle class loading to fail! From the error message, OC4J indicates that it is trying to load classes for Login and Candle using the classloader for Webservices.
    So, to summarize, once the webservices app runs an Axis2 servlet, OC4J tries to use the webservices' classloader to load classes for the other applications instead of using their classloaders. The example error message I give below is for the Candle application, but the same problem occurs for Login.
    Please help, even if it's just a suggestion for something to try!! We've been trying to understand this for 2 days and we're still as stumped as ever.
    [java] 2007-06-15 14:59:59,159 ERROR [org.apache.struts.action.RequestProcessor] - No action instance for path /adpThrowableHandler could be created
    [java] oracle.classloader.util.AnnotatedClassNotFoundException:
    [java] Missing class: com.adp.candle.core.ui.struts.exceptionhandler.AdpThrowableHandlerAction
    [java] Dependent class: org.apache.struts.util.RequestUtils
    [java] Loader: default.web.candle:0.0.0
    [java] Code-Source: /C:/build/javaroot/candle/WEB-INF/lib/struts.jar
    [java] Configuration: WEB-INF/lib/ directory in C:\build\javaroot\candle\WEB-INF\lib
    [java] This load was initiated at default.web.webservices:0.0.0 using the loadClass() method.
    [java] The missing class is available from the following locations:
    [java] 1. Code-Source: /C:/build/javaroot/candle/WEB-INF/classes/ (from WEB-INF/classes/ in C:\build\javaroot\candle\WEB-INF\classes)
    [java] This code-source is available in loader default.web.candle:0.0.0.
    -- Brad

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

  • Class.forName() with dynamic String

    I'm trying to create objects of a class whose name depends on a runtime database lookup. So my code looks like this:
    package com.mycompany.ourproduct.ourpackage;
    String className = rs.getString(1);
    Class c = Class.forName(className);
    When I run the program, I get a ClassNotFoundException. But everything runs fine if I replace the code above with this:
    package com.mycompany.ourproduct.ourpackage;
    // String className = rs.getString(1);
    String className = "com.mycompany.ourproduct.ourpackage.oursubpackage.MyClass"
    Class c = Class.forName(className);
    The problem seems to be in the dynamic linking. Although the class I'm trying to load is in a different package, it is a public class (and I can load it with a static string). Neither does moving it to the same package fix the problem.
    I've noticed that if I supply a mis-named class with a static string, the exception reads:
    java.lang.ClassNotFoundException: com.mycompany.ourproduct.misspelledpackage.SomeClass
    but the same exception prints as follows when the string comes from the database:
    java.lang.ClassNotFoundException: com/mycompany/ourproduct/misspelledpackage/SomeClass
    I thought the difference was one of compile-time linking and run-time linking, but oddly enough, I still get the dots for misspelled classes that I (1) supply on the command line, (2) read from a file, or (3) concatenate from command line arguments plus info from a file. It's just when I pull the class name from the database that I get the slashes. Does anyone know what's going on?
    Here's what I get from java -version:
    java version "1.2.2"
    Solaris VM (build Solaris_JDK_1.2.2_05a, native threads, sunwjit)
    Any help would be greatly appreicated!

    Hmm. Weird. Have you looked at the String you're getting back from the database? Does it have slashes or dots? (Should be dots.) Have you made sure any leading/trailing spaces have been trimmed? Try doing classname.equals("com.mycompany... etc.") to see if it really is the same string as the constant that does work.
    If it turns out the String is correct, and the only difference is whether that String came from a databaes or a literal, then I don't know what's going on. The first step, though, is to verify whether that's really the case, or if you're not getting the String you think you are.

  • Class.forName() throws null exception in servlet

    Hi, just wondering if anyone having this similar problem:
    when i try to load a class using Class.forName() method inside a servlet, it throws null exception.
    1) The exception thrown is neither ClassNotFoundException nor any other Error, it's "null" exception.
    2) There's nothing wrong with the code, in fact, the same code has been testing in swing before, works perfectly.
    3) I have include all necessary jars/classes into the path, even if i haven't, it should throw ClassNotFoundException instead, not "null" exception.

    I have tried to detect any possible nullable variable, and it is able to run until line 15. The exception thrown is actually null only... not NullPointerException... which is why i have confused...
    the message i received is "PlugInException: null".
    The code is at follow:
    * Load plugin
    * @return ArrayList of plugins
    * @exception PlugInException PlugInException
    01 public ArrayList loadPlugin()
    02 throws PlugInException
    03 {
    04 PlugIn plugin;
    05 ArrayList plugins = new ArrayList();
    06
    07 for (int i = 0; i < configLoader.getPluginTotal(); i++)
    08 {
    09 try
    10 {
    11 if (debugger > 0)
    12 {
    13 System.out.print("Loading " configLoader.getPluginClass(i) "...");
    14 }
    15 if (Class.forName(configLoader.getPluginClass(i)) == null)
    16 {
    17 if (debugger > 0)
    18 {
    19 System.out.print(" not found");
    20 }
    21 }
    22 else
    23 {
    24 if (debugger > 0)
    25 {
    26 System.out.println(" done");
    27 }
    28 plugin = (PlugIn)(Class.forName(configLoader.getPluginClass(i)).newInstance());
    29 plugin.setContainer(container);
    30 plugins.add(plugin);
    31 }
    32 }
    33 catch (Exception e)
    34 {
    35 throw new PlugInException("PlugIn Exception: " + e.toString());
    36 }
    37 }
    38
    39 return plugins;
    40 }

  • Class.forName() ????

    Hello, I have the following problem:
    1. I create a class with "Class comp1 = Class.forName(strName);"
    2. With creating an instance custom the constructor some parameters.
    3. With "Constructor[ ] myconstr = comp1.getConstructors();" I get all Constructors.
    4. With "Class[ ] paramTypes = myconstr.getParameterTypes();" I get the parameter types
    question: Can I find somehow parameter name?
    Thanks for your help!!!
    Hallo, ich habe folgendes Problem:
    1. Ich erzeuge eine Klasse mit "Class comp1 = Class.forName(strName);"
    2. Beim Erzeugen einer Instanz brauch der Konstruktor einige Parametern.
    3. Mit "Constructor[] myconstr = comp1.getConstructors();" bekomme ich alle Konsturktoren.
    4. Mit "Class[] paramTypes = myconstr[i].getParameterTypes();" kann ich die Parametertypen bekommen
    Frage: Kann ich irgendwie Parametername rausfinden?
    Vielen Dank f�r die Hilfe!!!

    A method signature consists of the methods name and the parameter types. Nothing more is stored in the class-files. So there is no way to address a parameter by it's name in java.
    You may want to do something like:
    Class[] paramTypes=new Class[] { A.class, B.class };
    Constructor constructor=C.class.getConstructor(paramTypes);
    C cObj= (C) constructor.newInstance(new Object[] ( a, b));

  • Weblogic is getting shutdown by calling Class.forName("className")

    Hi,
    I have written the following code and it's running thru a web application in Weblogic. The problem is when calling Class.forName(), the weblogic server 9.2 gets shutdown.
    final static private String[] uib_cn = {
    "com.realm.portal.cda.ui.UIBuilder",
    "com.realm.rcash.rcoll.cda.ui.RCollUIBuilder",
    "com.realm.rcash.rpay.cda.ui.RPayUIBuilder"
    static {
    // Init the Constructor object for each UI builder class
    for (int i = 0; i <uib_cn.length; i++) {
    try {
    Class<?> c = Class.forName(uib_cn);
    uic[i] = c.getConstructor(IRbacParamsBean.class);
    } catch (Exception e) {
    log.error(e.getMessage(), e);
    The class containing this code in a jar file, is trying to load at runtime other class files which are in separate jar but all the jars are in same location WEB-INF/lib.
    Plz anyone can help me why this is happening and how to resolve this?
    Thanks & Regards
    Chanchal

    Is it due to an unhandled exception in the static initializer block? Are those classes available?

  • Class.forName("AClassName") always yields in an exception

    Dear Experts
    I am trying to get a classname at runtime and Class c = Class.forName always returns an exception
    I will appreciate your help in this regard. Anyways the full code is as follows:
    interface MyInter
        void accept();
        void display();
    class IntegerSorter implements MyInter {
        public void accept()
            System.out.println("IntegerSorter....................");
        public void display()
            System.out.println("Displays IntegerSorter...........");
    class StringSorter implements MyInter {
        public void accept()
            System.out.println("StringSorter....................");
        public void display()
            System.out.println("Displays StringSorter.............");
    public class Main {
        public static void main(String[] args) {
            Class c=null;
            MyInter m=null;
            String s="IntegerSorter";
            try
                 c = Class.forName(s);
            } catch (Exception e1) {
                System.err.println(e1.getMessage());
            try {
                m = (MyInter) c.newInstance();
            } catch (Exception e) {
                System.err.println(e.getMessage());
            m.accept();
            m.display();
    }Edited by: standman on Mar 18, 2011 1:41 PM

    standman wrote:
    I am trying to get a classname at runtime and Class c = Class.forName always returns an exceptionThat's not enough information; which Exception?
    Plus, I ran your exact code o my machine, and got absolutely no exception. Are you posting the exact code that demonstrates the problem?
    try
    c = Class.forName(s);
    } catch (Exception e1) {
    System.err.println(e1.getMessage());
    }As an aside, don't log exceptions like that. Although it looks fine on so small a code, it's way not enough information if you have to debug such a "trace" in a non-trivial program.
    Instead log the exception's stack trace ( e1.printStackTrace() ), or use a logging library (for bigger programs).
    Regards,
    J.

  • ClassNotFoundException when using Class.forName(), thx

    in a study app, i try to use Class.forName() to load any class then get its properties (fields, methods etc. vs reflect).
    the (Frame based) app is in directory:
    c:\app\StudyApp.class
    there is a "Open class" button on the app, click the button, i use FileChooser to open any class file.
    i.e. open a class (assume it is not packaged)
    d:\dir\TheClass.class
    coding in StudyApp.java is:
    Class cls=Class.forName("TheClass");
    now a ClassNotFoundException throws when call Class.forName() above.
    it is easy to understand why throw the exception because i never tell where the class is. it is in directory
    d:\dir
    my question is: how to tell VM the directory.
    the directory d:\dir can not be applied to -classpath when run java.exe StudyApp, because the directory is random one at run-time.
    i tried to change System property (i.e. "java.class.path", 'user.dir" etc. none of them can fix the problem.
    thanks in advance for any help

    This probably does a lot more than you need:
    import java.util.*;
    import java.io.*;
    import java.util.jar.*;
    import java.lang.*;
    public class ClassFileFinder extends ClassLoader
         List cpath = new LinkedList();
         void addFile(File f) {
              if(f.isDirectory() || (f.isFile() && f.canRead() &&
                                          f.getName().endsWith(".jar")))
                   cpath.add(f);
         public byte[] classData(String className)  {
              String cname = className.replace('.', File.separatorChar) + ".class";
              Iterator it = cpath.iterator();
              while(it.hasNext()) {
                   File f = (File)it.next();
                   try {
                        if(f.isDirectory()) {
                             File cFile = new File(f, cname);
                             if(cFile.isFile()) {
                                  byte[] buf = new byte[(int)cFile.length()];
                                  InputStream in = new FileInputStream(cFile);
                                  int off  = 0, l;
                                  while((l = in.read(buf, off, buf.length - off)) > 0) {
                                       off += l;
                                       if(off >= buf.length) break;
                                  in.read(buf);
                                  in.close();
                                  return buf;
                        } else if (f.isFile()) {
                             JarFile jar = new JarFile(f);
                             JarEntry ent = jar.getJarEntry(cname);
                             if(ent != null) {
                                  byte[] buf = new byte[(int)ent.getSize()];
                                  int off = 0, l;
                                  InputStream in = jar.getInputStream(ent);
                                  while((l = in.read(buf, off, buf.length - off)) > 0) {
                                       off += l;
                                       if(off >= buf.length) break;
                                  in.close();
                                  return buf;
                   } catch (IOException e) {
              return null;          
         public Class findClass(String className) throws ClassNotFoundException{
              byte[] data = classData(className);
              if(data == null)
                   return getParent().loadClass(className);
              else
                   return defineClass(className,data,0, data.length);
    }Create an instance, Add directories and/or jar files with addFile then loadClass the class you want.

  • Class Casting problem

    hi,
    i�ve loaded a class at runtime and to parse it to another type, also loaded at runtime, but an error occures!
    in this code i dont write the try�s and catches, they doesn�t matter in this problem
    Class prototype; //source class
    Class parser;    //target class
    Class parsed;    //parsed class (source -> target / prototype -> parser)
    prototype = Class.forName("Prototype");
    parser    = Class.forName("Parser");
    parsed    = (parser) prototype; //Compiler: "Class parser not found"what does it mean?
    can somebody help me?
    thx anyway
    cu Errraddicator

    parser    = Class.forName("Parser");
    parsed    = (parser) prototype; //Compiler: "Class1st. "Parser" or "parser" ... what's the name of your class?
    2nd. all your variables are of type Class. why would you want something of type Class cast into type Parser and then assign it back to a variable of class parsed?
    try something like:
    Class parserClass = Class.forName("Parser");
    Parser parser = (Parser) parserClass.newInstance();of course this is not really THE way to construct an object if you know about the Class type beforehand....
    ulrich

  • Can't load class with Class.forName()

    Hi, can somebody help me with this problem. I have clas copiled with jdk 1.3.1 (I also test it with jdk 1.4.1). If I try to load a Class instance with Class.forName("package.app.MyClass)") I have a runtime exception:
    java.lang.ClassNotFoundException: com.unisys.ebs.all.ispecs.GD130IspecModel
         at java.net.URLClassLoader$1.run(URLClassLoader.java:195)
         at java.security.AccessController.doPrivileged(Native Method)
         at java.net.URLClassLoader.findClass(URLClassLoader.java:183)
         at java.lang.ClassLoader.loadClass(ClassLoader.java:294)
         at java.lang.ClassLoader.loadClass(ClassLoader.java:250)
         at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:310)
         at java.lang.Class.forName0(Native Method)
         at java.lang.Class.forName(Class.java:115)
         at com.unisys.util.ObjectLoader.load(ObjectLoader.java:60)
         at com.unisys.jellybeans.IspecFactory.getIspec(IspecFactory.java:74)
         at com.unisys.jellybeans.LINCEnvironment.getIspec(LINCEnvironment.java:1012)
         at com.unisys.ebs.middleware.TestLinc.initConnection(TestLinc.java:52)
         at com.unisys.ebs.middleware.TestLinc.main(TestLinc.java:106)
    but if instead of this I instantiate the class calling the constructor and writing an import sentence, it works fine. I really need to instantiate this class via Class.forName because it extends a superclass and know the class to instantiate only at runtime. I will appreciate any help. Thanks.
    Pablo Antonioletti

    I removed the import in the file header and wrote this code:
    try{           
    ispecModel = new com.unisys.ebs.all.ispecs.GD130IspecModel();
    Class ispecClass = Class.forName("com.unisys.ebs.all.ispecs.GD130IspecModel.class");
    catch(Exception e)
    e.printStackTrace();
    the new sentence work fine, if write mor code I can access methods and members. When the runtime execute the Class.forName sentence the exception is thrown. I put all in the same file and class to avoid mistakes typing class path.
    This is very rare I never seen it before and I developed java application since five years ago.

  • Help! JSP w/ struts can't find Class.forName("com.mysql.jdbc.Driver")

    I think this is just a directory structure issue but I can't figure it out. I am writing a JSP / Struts / MYSQL web application which uses the mysql JDBC connector. The connector (mysql-connector-java-5.1.6-bin.jar) is in the referenced libraries. If I write the line of code:
    Class.forName("com.mysql.jdbc.Driver");
    To load up the driver, it works in JSP files in the folder /projectname/webroot/web-inf just fine and I can go on to execute MySQL queries. However, I need to load up the driver in an action (.java action) with the directory structure /projectname/src/action and it throws the exception "class not found", I believe, it can no longer seem to get to the driver. Can anyone tell me how to resolve this problem?
    Thanks in advance, I hope this is the correct place (I have done my best to find the right one).
    Edited by: Arkanin on Apr 24, 2008 4:39 PM

    Arkanin wrote:
    I think this is just a directory structure issue but I can't figure it out. I am writing a JSP / Struts / MYSQL web application which uses the mysql JDBC connector. The connector (mysql-connector-java-5.1.6-bin.jar) is in the referenced libraries. Nope, it's not. I don't know what "referenced libraries" means. It has to be in CLASSPATH, and that isn't an environment variable.
    If I write the line of code:
    Class.forName("com.mysql.jdbc.Driver"); No, wrong.
    The JAR file for the Driver class might go in the WEB-INF/lib of your web app. If you're using Tomcat 5.5.26, put it in common/lib.
    %

  • Need Help Loading Sqlbase Driver Using Class.forName(...

    I'm having trouble connecting to a Sqlbase database on my PC. The problem seems to be with loading the driver with the "Class.forName" method. My source code (listed below) is in the "C:\My Documents\java" folder. I installed the Sqlbase driver in "C:\com\centurasoft\java\sqlbase" folder. The driver installation modified my autoexec.bat file to include the line "SET CLASSPATH=C:\com\centurasoft\java\sqlbase".
    The epdmo database is in a folder on my D:\ drive.
    It seems to find the SqlbaseDriver.class file, but for some reason it can't load it. I would greatly appreciate any suggestions as to how I can fix this.
    With the line -- Class.forName("centura.java.sqlbase.SqlbaseDriver");
    The SqlbaseEx.java program will compile, but I get the following error
    when I try to run it:
    Exception in thread "main" java.lang.NoClassDefFoundError: SqlbaseDriver (wrong name: com/centurasoft/java/sqlbase/SqlbaseDriver)
    at java.lang.ClassLoader.defineClass0(Native Method)
    at java.lang.ClassLoader.defineClass(Unknown Source)
    ... [several more lines like these]
    at SqlbaseEx.main(SqlbaseEx.java:25)
    With the line -- DriverManager.registerDriver(new SqlbaseDriver());
    The SqlbaseEx.java program will NOT compile. I get the following error:
    SqlbaseEx.java:21: cannot access SqlbaseDriver
    bad class file: C:\com\centurasoft\java\sqlbase\SqlbaseDriver.class
    class file contains wrong class: com.centurasoft.java.sqlbase.SqlbaseDriver
    Please remove or make sure it appears in the correct subdirectory of the classpath.
    Also, does the line -- String url = "jdbc:sqlbase:epdmo";
    look OK? I've seen numerous examples and they all have some values separated by slashes //. Am I
    missing something here that will bite me when I get past this driver loading error?
    import java.sql.*;
    // Create the ...
    public class SqlbaseEx {
    public static void main(String args[]) {
    String url = "jdbc:sqlbase:epdmo";
    Connection con;
    String createString;
    createString = "create table COFFEES " +
    "(COF_NAME varchar(32), " +
    "SUP_ID int, " +
    "PRICE float, " +
    "SALES int, " +
    "TOTAL int)";
    Statement stmt;
    try {
    Class.forName("centura.java.sqlbase.SqlbaseDriver");
    // DriverManager.registerDriver(new SqlbaseDriver());
    } catch(java.lang.ClassNotFoundException e) {
    System.err.print("ClassNotFoundException: ");
    System.err.println(e.getMessage());
    try {
    con = DriverManager.getConnection(url, "SYSADM", "SYSADM");
    stmt = con.createStatement();
    stmt.executeUpdate(createString);
    stmt.close();
    con.close();
    } catch(SQLException ex) {
    System.err.println("SQLException: " + ex.getMessage());

    Thanks for the reply.
    Upon further testing, I think my original post was slightly incorrect: if I use either of the following lines --
    Class.forName("com.centurasoft.java.sqlbase.SqlbaseDriver");
    or
    Class.forName("centura.java.sqlbase.SqlbaseDriver");
    I get the following error at runtime:
    ClassNotFoundException: com.centurasoft.java.sqlbase.SqlbaseDriver
    or
    ClassNotFoundException: centura.java.sqlbase.SqlbaseDriver
    It is when I use the line -- Class.forName("SqlbaseDriver");
    that I get the long error message in my original post.
    I don't understand why it can't find/load the driver. I feel like I've covered all the bases -- I've tried numerous variations of the driver name in the Class.forName method, my classpath variable seems to be set correctly. Does it matter what folder I compile my program in? Right now, I've just been compiling it in the same folder as the driver file -- c:\com\centurasoft\java\sqlbase.

Maybe you are looking for