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.

Similar Messages

  • Not able to work with Class.forName

    I am trying to use Class.forName() from a string which is passed to me as argument.
    Class batchClass = Class.forName(args[1]);
    A jar file contains the class file for the string received above and I have this jar file in the manifest of my executable jar.
    I get a class not found exception when I run my executable jar
    Can some body give pointers..what could possibly be the issue.
    The jar file is in my classpath
    Message was edited by:
    chabhi

    run script
    #!/bin/csh
    java -jar -DDBPROVIDER=NO -DDBUS_ROOT=$DBUS_ROOT -DVTNAME=$VTNAME ./jar/IntraDayDepotPositionBatch.jar MagellanStart IntraDayDepotPositionBatch INPUTFILE LOGFILE
    Exception
    Magellan program starting - program class IntraDayDepotPositionBatch
    Cannot find program class - IntraDayDepotPositionBatch
    IntraDayDepotPositionBatch
    java.lang.ClassNotFoundException: IntraDayDepotPositionBatch
    at java.net.URLClassLoader$1.run(URLClassLoader.java:200)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:268)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:251)
    at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:319)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:164)
    at com.db.mmrepo.app.IntraDayDepotPositionBatch.MagellanStart.main(Unknown Source)
    THanks for your time on this issue,,,,

  • How does Class.forName() get a driver registered with DriverManager

    From the documentation, Class.forName() tends to loads the specified class via the class loader. But if we use it to load the class of a jdbc connection driver, how does it get automatically registered with DriverManager?
    Neerav

    yorkroad wrote:
    No. Class.ForName("whatever") intializes the class. As for registering it with the DriverManager, this is from the API:
    When the method getConnection is called, the DriverManager will attempt to locate a suitable driver from amongst those loaded at initialization and those loaded explicitly using the same classloader as the current applet or application.
    You could use DriverManager.registerDriver (new oracle.jdbc.driver.OracleDriver()); which does it all in one. (Although keep in mind that will require an Oracle import in your code!)
    m
    Edited by: yorkroad on Nov 4, 2009 3:42 PMNo, loading the Class with Class.forName already registers the driver, as already said. Where DriverManager "searches" is among those registered classes. The method detailed above does not do anything more than simply calling Class.forName() with the added drawback that the Driver jarfile must be present at compile time, and, in order to change DBs you would have to change and recompile your code.

  • How to use class.forName

    I am trying to use Class.forName() from a string which is passed to me as argument.
    Class batchClass = Class.forName(args[1]);
    A jar file contains the class file for the string received above and I have this jar file in the manifest of my executable jar.
    I get a class not found exception when I run my executable jar
    Can some body give pointers..what could possibly be the issue.
    The jar file is in my classpath
    run script
    #!/bin/csh
    java -jar -DDBPROVIDER=NO -DDBUS_ROOT=$DBUS_ROOT -DVTNAME=$VTNAME ./jar/IntraDayDepotPositionBatch.jar MagellanStart IntraDayDepotPositionBatch INPUTFILE LOGFILE
    Exception
    Magellan program starting - program class IntraDayDepotPositionBatch
    Cannot find program class - IntraDayDepotPositionBatch
    IntraDayDepotPositionBatch
    java.lang.ClassNotFoundException: IntraDayDepotPositionBatch
    at java.net.URLClassLoader$1.run(URLClassLoader.java:200)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:268)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:251)
    at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:319)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:164)
    at com.db.mmrepo.app.IntraDayDepotPositionBatch.MagellanStart.main(Unknown Source)
    Thanks for your time and feedback on this

    actually i tried both...with package name and without package name..
    nothing worked...
    my manifest file also contains the path to the package..so does the classpath

  • Trouble w/ multiple applets dynamically starting and Class.forName()

    I'm trying to start applets dynamically and I see strange behavior on some systems it works fine and gets the applet class from the jar file. On other systems it makes an http request back to the server to try and get the class. I don't know where in the Class or ClassLoader it's deciding whether to get this class from the jarfile or from the server and all of these classes are contained in the jarfile? Any suggestions?
    Here's the method to start new applets
    public Component startApplet( String className ) {
    System.out.println("Starting applet "+className);
    Class appletClass = null;
    JApplet japplet = null;
    try {
    appletClass = Class.forName("com.actsolar.ui.applet."+className);
    System.out.println(appletClass);
    japplet = (JApplet)appletClass.newInstance();
    japplet.init();
    } catch (Exception e) {
    System.out.println("startapplet Exception: "+e.getMessage());
    return japplet;
    thanks,
    andrew

    Hi,
    I have seen the same problem when I mix up small letters and BIG LETTERS.
    Ex :
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
    <applet code="Function3.class"width="100" height="100">
    </applet>
    </html>
    will work with Function3.class
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
    <applet code="function3.class"width="100" height="100">
    </applet>
    </html>
    Will NOT work.
    Maybe this will help you , I am also new on JAVA so maybe you make the same mistake like I did ?
    Best Regards,
    Didier.

  • Problem with Dynamically accessing EJB Class objects in WL 7.0 SP1

    I am trying to build a component which has the ability to instantiate and execute
    an known EJB method on the fly.
    I have managed to build the component but when I try and execute it I get a ClassNotFoundException.
    I know that the EJB I am trying to invoke is deployed and available on the server,
    as I can see it in the console, I also seen to have been able to get the remote
    interface of the object, my problem occurs when I try and access the class object
    so I can perform a create on the object and then execute my method
    The code I have written is below:
    private Object getRemoteObject(Context pCtx, String pJNDIName, String pHomeBean)
    throws Exception {
         String homeCreate = "create";
         Class []homeCreateParam = { };
         Object []homeCreateParamValues = {};           
    try {  
    //This call seems to work and doesn't throw an exception     
    Object home = pCtx.lookup(pJNDIName);
    //However this call throws a java.lang.ClassNotFoundException
    Class homeBean = Class.forName(pHomeBean);
    Method homeCreateMethod = homeBean.getMethod(homeCreate,homeCreateParam);
    return homeCreateMethod.invoke(home, homeCreateParamValues);
    } catch (NamingException ne) {             
    logStandardErrorMessage("The client was unable to lookup the EJBHome.
    Please make sure ");
    logStandardErrorMessage("that you have deployed the ejb with the JNDI
    name "+pJNDIName+" on the WebLogic server ");
    throw ne;
    } catch (Exception e) {
    logStandardErrorMessage(e.toString());
    throw e;     
    Any advice would be really appreciated, I'm fast running out of ideas, I suspect
    it has something to do with the class loader but I'm not sure how to resolve it
    Regards
    Jo Corless

    Hello Joanne,
    Congratulations! I'm very happy that you've managed to fix your problem. It's
    always essential to understand how to package applications when deploying on BEA
    WebLogic. Usually, by throwing everything into an EAR file solves just about all
    the class loader problems. :-) Let us know if you have any further problems that
    we can assist you with.
    Best regards,
    Ryan LeCompte
    [email protected]
    http://www.louisiana.edu/~rml7669
    "Joanne Corless" <[email protected]> wrote:
    >
    >
    I've fixed it!!!!!!!!
    Thanks to everyone who gave me help!!!!
    The class loader was the culprit which is what I suspected all along.
    As soon
    as I put the 2 jar files I was using into an EAR file the problem went
    away!!!!!
    Thanks again
    Jo Corless
    "Ryan LeCompte" <[email protected]> wrote:
    Hello Joanne,
    As Mr. Woollen mentioned, I also believe it's a problem with the class
    loader.
    You need to be careful how you arrange your EJBs, because WebLogic has
    a specific
    method in which it loads classes in an EAR, JAR, and WAR file(s). Please
    refer
    to http://dev2dev.bea.com/articles/musser.jsp for more information about
    BEA WebLogic
    class loading mechanisms and caveats. Also, try printing out the various
    methods
    that are available on the object that was returned to you via reflection.
    For
    example, use the getMethods() method, which returns an array of Method
    objects
    that you can subsequently cycle through and print out the various method
    names.
    This way you can discover if the class found/returned to you is indeed
    the one
    you intend to locate.
    Hope this helps,
    Ryan LeCompte
    [email protected]
    http://www.louisiana.edu/~rml7669
    Rob Woollen <[email protected]> wrote:
    I believe the issue is the home interface class for this EJB is not
    available in the class loader which is doing the reflection.
    If you do:
    getClass().getClassLoader().loadClass(homeInterfaceClassName)
    I suspect it will fail. Reflection still requires that the class be
    loadable.
    -- Rob
    Joanne Corless wrote:
    Hi Slava,
    If I make my code look like you describe below I get a compliationerror telling
    me that
    home.getMethod() is not recognised (no such method)
    If I change it slightly and use
    Method homeCreateMethod =
    home.getClass().getMethod(homeCreate,homeCreateParam);
    The code will compile OK but when executed it still throws a NoSuchMethodException
    Any ideas ?
    Thanks for your help so far
    Regards
    Jo Corless
    Your code should look like
    Object home = pCtx.lookup(pJNDIName);
    Method homeCreateMethod =
    home.getMethod(homeCreate,homeCreateParam);
    return homeCreateMethod.invoke(home, homeCreateParamValues);
    Regards,
    Slava Imeshev
    "Joanne Corless" <[email protected]> wrote in message
    news:[email protected]...
    Hi Ryan,
    I also wanted to mention that if you do a "header search" in this
    particular
    newsgroup
    with the search query as "reflection", you will see many previousmessages
    regarding
    reflection and EJBs. I believe you could learn a lot from thedifficulties
    that
    others have faced and solved.I tried that and although there was a number of similar cases noneof them
    actually
    seem to fix my issue. Thanks for the suggestion though
    Are the EJBs that you are trying to access accessible via your
    system
    classpath?
    Try to avoid having them accessible via the main system classpath,and
    only bundle
    them in your appropriate EJB jar files (contained in an EAR file,for
    example).Maybe I should have laid the problem out a little clearer.
    I have a number of EJB's bundled up in a JAR file which is hot deployedto
    the
    server. Within this first JAR file is an EJB (SSB) component that
    needs
    to
    be
    able to invoke a known method on another EJB. This second EJB may
    or
    may
    not be
    within the first JAR file but it also will be hot deployed.
    The component trying to invoke the method on the 2nd EJB has to
    be
    able to
    create
    an instance of the 2nd EJB without actually knowing anything bar
    a
    JNDI
    Name which
    is passed in at runtime.
    I can get as far as doing the
    Object home = pCtx.lookup(pJNDIName);
    This returned a class with the name
    "com.csc.edc.projects.allders.httppostoffice.postman.PostmanBean_mp8qy2_Home
    Impl_WLStub"
    My problem seems to occur when I try and invoke the create method
    Method homeCreate = home.getClass().getMethod("create", new Class[0]);
    My code throws a java.lang.NoSuchMethodException at this point so
    I
    am
    unable
    to progress to the next step of :
    Object bean = homeCreate.invoke(home, null);
    So I can return the instantiated bean back to the calling client.
    Why am I getting the NoSuchMethodException, is is because I am gettinga
    stub
    back rather than the home interface and if so how do I get the truehome
    interface
    from the bean
    Thanks in advance
    Jo Corless

  • Help accessing methods in classes load with forName()

    Hi all,
    I am dynamically loading classes at runtime by using Class.forName() and .newInstance(). Is there any way I can access the methods of those classes after they are dynamically loaded? It doesnt seem that they are available for use.
    Any help would be appreciated.
    Ryan

    To clarify, are you asking how to invoke a method on an Object without knowing its class? In any case you should use the reflection api that are avaliable.
    Ex: cl = Class.forName(); Method[] methods = cl.getMethods(); for(int i = methods.length; i-- > 0;) System.out.println(methods[i-1].getName());
    or
    methods[i-1].invoke(cl.newInstance(), new Object[]{});

  • Question  about dynamic class loading with thread built in

    Hi ,
    I am trying to load a class with a thread built in from the network.
    I write my network classloader, convert the class to a byte array and transmit over the network using socket. This step seems fine but when I tried to load the class at the receiver, some exception happens,"
    the reported exception is that :
    Exception in thread "Thread-2" java.lang.NoClassDefFoundError: SampleProject/Application$1
    my class name is "SampleProject . Application", the $1 I think it may refers to the thread built in the "Application".
    Could any one give me some hint for how to dynamic load such class file with thread built in over the network?
    Thank you!
    Best Regards,
    Song Guo

    Exception in thread "Thread-2"
    java.lang.NoClassDefFoundError:
    SampleProject/Application$1That means that the receiving end can't find an anonymous inner class which you have in the Application class. (The anonymous clas is given the synthetic name 1). Check your bin/classes folder you will have a class there with the name Application$1.class
    Kaj

  • Dynamic String Substitution in Eclipse with JSP

    Hi folks,
    I'm wondering if it is possible to dynamically change token for ant that are present in my jsp with the dynamic string substitution in jsp inside tomcat. Right now, I'm loading the bootstrap with my runner and pointing to my application. In preference, I've put some token like @STATIC_URL@ that should replace by something else. But It seem that Tomcat goes directly to the source of the jsp and does'nt really care about the string substition of eclipse. Is there a way to do that?

    Hi there,
    Since this is more of an Ant or an Eclipse question it is better to post the question in those forums / mailing lists as people on those lists will be able to help you better:
    Here's the link to subscribe to the Ant User Mailing List, once you subscribe send a new e-mail to the list:
    http://ant.apache.org/mail.html
    Forum for Eclipse:
    http://www-128.ibm.com/developerworks/forums/dw_forum.jsp?cat=28&forum=472

  • Class.forName() doesn't take dynamic class name

    String name="";
    String country="";
    String className = name + "_" + language + "_" + country;
    Class thisClass = Dynamicclassload.classLoad(className);
    System.out.println(className);
    Class class1 = Class.forName(className);
    child = (ResourceBundle) class1.newInstance();
    child.setParent( bundle );
    bundle = child;
    System.out.println("I am here");
    As i am passing classname as variable it throws an exception class not found exception.but if we write class name as the parameter of class.forName().it works.i am implementing in j2me
    why this happen? give me solution.

    The following classpackage test;
    public class TestLoad {
        String aString = "This is a Test";
        Integer anInteger = new Integer(42);
        public TestLoad() {
            System.out.println("aString = " + aString + ", anInteger = " + anInteger);
    }works correctly when loaded and instantiated by this class:package test;
    import java.util.logging.Logger;
    public class ExecuteTest {
        public static final Logger log = Logger.getAnonymousLogger();
        public static void main(String[] args) {
            try {
                Class clazz = Class.forName("test.TestLoad");
                TestLoad test = (TestLoad) clazz.newInstance();
            } catch (Exception ex) {
                log.severe(ex.toString());
    }and produces the string "aString = This is a Test, anInteger = 42"
    I used the following version of Java on Windows 2000
    java version "1.4.0"
    Java(TM) 2 Runtime Environment, Standard Edition (build 1.4.0-b92)
    Java HotSpot(TM) Client VM (build 1.4.0-b92, mixed mode)

  • (Class ? extends Set String ) Class.forName("example.SetImpl").asSubclass

    Is there a way to do the following without an Unchecked cast?
    Class<? extends Set<String>> clazz;
    clazz = (Class<? extends Set<String>>) Class.forName("example.SetImpl").asSubclass(Set.class);
    Set<String> mySet = clazz.newInstance();
    cheers,
    reto

    No. The last line will always generate that warning making the second line pointless. There is no way to create a new instance of a generic class because there is (for most intents and purposes) no such thing as a generic class at runtime.

  • Having trouble with Class.forName & Class.newInstance

    i have a string name of a JPanel class i want to place on a TabbedPane. the JPanel class is in another package, that i import.
    i have been trying all kinds of ways to do this, and it is not working. does anyone have any ideas on how to do this?
    i need: myTabPane.addTab("financial calc", new myBzPanel());
    i tried: myTabPane.addTab("financial calc", Class.newInstance(Class.forName("myBzPanel()"));
    without any success.
    any ideas appreciated. thanks.

    The Class.newInstance() method does not take any arguement and you passed a wrong stuff to the Class.forName(String) method.
    Class c = Class.forName("mypackage.myBzPanel");
    myBzPanel bz = (myBzPanel)c.newInstance();
    myTabPane.addTab("financial calc", bz);

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

  • What to do with Class.forName(), Class.getName() when Obfuscating

    hi,
    I have been asked at my company to perform Obfuscation of our project-code, The problem I have been facing is,
    We have got too many Class.forName(), Class.getName() calls in our Project-code, which is really hindering the process of Obfuscating all the Classes (refrences in code may break for all these classes which are dynamically being asked for, hence the project may suffer). And it is a pain-in-neck to really resolve which classes to exclude so that code should not break after obfuscation.
    What my question is:
    Do we have some automated tool to take care of all these Reflection API calls, so that work left to us is minimal?
    If not, Do we have some short-cut (program, tool etc.) to identify all the classes which should be excluded?

    Which program are you using when obfuscating?
    In RetroGuard you can for example avoid certain class names, or packages, to be obfuscated.

  • Class.forname - Unable to load class if two jars with same package name

    class.forname - Unable to load class if two jars contains same package name exists in classpath.
    JVM is stopping search for class one it finds the package name in the jar file that is ahead in classpath,
    JVM is not continuing search in the remaining jar files.
    For this , I put the jar file that contained class ahead of of ther jar file containing same package name, then it worked.
    Is this a JVM bug ? (JDK 1.5)

    I reported as bug to sun. I got auto email, looks they have not assigned any Bug ID so far.

Maybe you are looking for

  • Importing to I-Movie - lost sound AND video

    Hi. I have a feeling this has already been answered but here goes: I recorded some video on my Sony still camera in MPEG format (.mpg files). They worked fine in I-photo. When I imported them into Imovie though, I not only lost sound but it would see

  • BP replication from CRM to R/3

    Dear All, Is there a way to assign R/3 account groups during BP creation in CRM. i.e When I create a BP in CRM, system should assign it to one out of many available account groups based on a user defined condition. In PIDE I can maintain an Account g

  • My "most visited" list disappeared. How do I get it back?

    The list of my most visited sites disappeared. I used to be able to go to my business site and my bank with just one click, I 'd like to be able to do that again.

  • Runs slow & locks up plus can't windows update & upgrade to professional

    HP 6250 desktop running windows seven. problems started after replacing hard drive.   Help please.....

  • Use Automator/AppleScript to clean iPhoto Library

    Hello, Having read a lot of posts about the use of AppleScript and Automator to do things with iPhoto, I think it's possible to create a script or a processus to clean the iPhoto Library (let say, a copy of it) to eliminate "zombie files" (photos whi