Class.forName() debunked

This issue is about: Dynamic loading and Inheritance.
Debugging an odd ClassNotFoundException in a J2EE Application, I was involved investigating deeply Class.ForName(). This method - namely the version with only the class name as parameter - is used inside xsdbeans.jar, an optiopnal library, shipped with IBM WebSphere 5.x. Moving the jar from the EAR classloader to the server runtime classloader caused weird behavior on my app.
I try to simplify the core question:
Suppose class E extends B. Base class B declares an instance method, dynLoad(String name) that uses internally Class.forName(String name).
Say 'e' an instance of E. Invoking e.dynLoad("Foo"), Class.forName("Foo") should use the ClassLoader of current class. But which is the 'current class': E or B? Is it the class of current object (E) or the declaring superclass (B)?
My instinctive answer was: E. But my J2EE app was behaving as the current class was B. Indeed E and B may be defined by different classloaders, and this makes a big difference.
A rapid lookup at Sun's docs confirmed my first hypothesis:
http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Class.html#forName(java.lang.String)
> Returns the Class object associated with the class or interface with the given string name.
Invoking this method is equivalent to:
Class.forName(className, true, currentLoader)
where currentLoader denotes the defining class loader of the current class.
ok, this is a little misleading, but going on:
http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Class.html#forName(java.lang.String,%20boolean,%20java.lang.ClassLoader)
> For example, in an instance method the expression:
>
Class.forName("Foo")
is equivalent to:
Class.forName("Foo", true, this.getClass().getClassLoader())
Not equivocal. The current class is the class of current object, no matter (apparently) if the instance method is declared in a superclass.
Right? Wrong. Here a minimal counter-example:
//-- B.java
import java.net.*;
public class B {
    public void dynLoad(String name) throws Exception {
        System.out.println(getClass().getSuperclass()
            + " defining classloader is: "
            + getClass().getSuperclass().getClassLoader());
        System.out.println(getClass()
            + " defining classloader is: "
            + getClass().getClassLoader());
        System.out.println("\n1) Class.forName(\""+name+"\");");
        // Loading with 'currentLoader'
        Class.forName(name)
            .newInstance();
        System.out.println("\n2) Class.forName(\""+name
            +"\", true, this.getClass().getClassLoader());");
        // This should be equivalent (by Sun J2SE API spec)
        Class.forName(name, true, this.getClass().getClassLoader())
            .newInstance();
    public static void main(String[] args) {
        ClassLoader syscl = ClassLoader.getSystemClassLoader();
        if (!URLClassLoader.class.isInstance(syscl)) {
            System.err.println("Cannot continue the trick.");
            System.exit(1);
        URL[] urls = ((URLClassLoader)syscl).getURLs();
        // Yet Another ClassLoader
        URLClassLoader yacl = new URLClassLoader(urls) {
            // Force Parent-last delegation policy to assure
            // demanded classes are defined by _this_ classloader
            public Class loadClass(String name)
                throws ClassNotFoundException {
                Class c = findLoadedClass(name);
                if (c == null) {
                    try {
                        // Simulate no visibility to base class to assure
                        // it is _not_ defined by this classloader too
                        if (name.equalsIgnoreCase("B")) {
                            throw new ClassNotFoundException();
                        c = findClass(name);
                    } catch (ClassNotFoundException e) {
                        c = getParent().loadClass(name);
                return c;
        try {
            // Loading class E with a different classloader
            Class c = yacl.loadClass("E");
            c.getMethod("dynLoad", new Class[]{String.class})
                .invoke(c.newInstance(), new Object[]{"Foo"});
        } catch (Exception ex) {
            ex.printStackTrace();
            System.exit(1);
//-- E.java
public class E extends B {
//-- Foo.java
public class Foo {
  public Foo() {
    System.out.println(getClass()
      + " defining classloader is: "
      + getClass().getClassLoader());
}Running above B.main() produce the following output on Sun JDK 1.3, 1.4.2, 1.5:
> class B defining classloader is: sun.misc.Launcher$AppClassLoader@3d200480
class E defining classloader is: B$1@3d2c0480
1) Class.forName("Foo");
class Foo defining classloader is: sun.misc.Launcher$AppClassLoader@3d200480
2) Class.forName("Foo", true, this.getClass().getClassLoader());
class Foo defining classloader is: B$1@3d2c0480
The evidence is that classloader used is not the same. in the case 1) it uses the classloader of superclass B. Hence the two form of Class.forName() invocation are not equivalent, as stated in Sun documentation.
Disclosure
The evidence is confirmed and explained looking at Sun's implementation of java.lang.Class.java and java.lang.ClassLoader.java: finally the Class.forName(String name) relies on sun.reflect.Reflection.getCallerClass(int) to find the famous 'current class' mentioned in the javadocs. This undocumented method returns the i-th caller class of current stack frames; each stack frame represents a method invocation coupled with its declaring class.
I wonder why in Sun docs this poorly explained issue was remaining immutable from 1.3 to date. Furthermore: which was the intended behavior? Another reason to the long said "Class.forName() is evil..." or am I missing something?
regards, Lorenzo

Of course, it comes down to the question: What is the current class?
Not something well defined. You are looking for this.getClass(), it's taking the class at compile time. If it went your way, woundn't that create an inconsistency in forName in static vs instance contexts?
Actually I think the static approach is more natural, because it means that forName behaves the way that resolving external references work. Your way would also go against the spirit of Java security policies which requires references down the classloader chain something to be treated with suspision.
The mechanism intended, I think, for these situations is the contextClassLoader property of Thread. When executing plugin type code the contextClassLoader should be set to the ClassLoader that loaded the plugin, and any references to resources or dynamic class loads from the plugin should be made using the contextClassLoader. This enables your shared library code to access classes and resources on behalf of the plugin code with access to classes and resources inside the plugin.
Thus, if you write library code or other container stuff likely to be called from a plugin you should probably always use:
Class cls = Thread.currentThread().getContextClassLoader().loadClass("foo");

Similar Messages

  • Class.forName, how to use it in the case?

    we have a java application:
    c:\app\TestForName.class
    inside the app, there is a call:
    Class.forName("ClassLib");
    ClassLib.class is a simplest class for testing with no package.
    ClassLib.class can be in any directory except the app's directory
    c:\app
    because ClassLib.class stands for our library class for multiple projects and multiple uses, it is not allowed to be in a special app directory.
    and, ClassLoader and URLClassLoder are not suitable in our case.
    i tried following 3 ideas, none of them is OK, please help.
    1. put ClassLib.class in directory
    c:\lib\
    (that is c:\lib\ClassLib.class)
    call application with command -cp
    java -cp c:\lib;....; TestForName
    (method Class.forName("ClassLib") call is inside TestForName.class)
    2. put ClassLib.class in
    c:\jdk\bin\
    (VM says it is one of "java.library.path")
    java -cp ....; TestForName
    3. put ClassLib.class in
    c:\jdk\JAR\classes\
    (VM says if is one of "sun.boot.class.path")
    java -cp ....; TestForName
    i really wondering how to make Class.forName() call successfuf inside application TestForName.class
    1. which directory is right place for ClassLib.class
    2. how to change command line or java code inside TestForName.class
    thx for any help.

    Why don't u use a class loader. Try this code
    // loader class
    public class Loader  extends ClassLoader {
        String path;
        public Loader(String path) {
              this.path = path;
        public Class findClass(String name) {
            byte[] b = loadClassData(path+name+".class");
            return defineClass(name, b, 0, b.length);
        private byte[] loadClassData(String name) {
            File file = new File(name);
            byte[] data = null;
            try {
                InputStream in = new FileInputStream(file);
                data = new byte[ (int) file.length()];
                for (int i = 0; i < data.length; i++) {
                    data[i] = (byte) in.read();
            catch (IOException ex) {
            file = null;
            return data;
    // in your caller class use
       Loader loader = new Loader(libPath); // lib path may be taken from a command line arg
       Object main = loader.loadClass("ClassLib", true).newInstance();I think this is what u r looking for
    Uditha Nagahawatta

  • Error in Class.forName("com.mysql.jdbc.driver")

    Hi forum,
    Please help me to solve the issue.
    im using the following jsp code for genrating the reports using JASPER REPORTS
    the JSP FILE
    <%@ page contentType="text/html;charset=windows-1252"%>
    <%@ page import="java.io.*"%>
    <%@ page import="java.util.*"%>
    <%@ page import="java.sql.*"%>
    <%@ page import="javax.sql.DataSource"%>
    <%@ page import="javax.naming.InitialContext"%>
    <%@ page import="net.sf.jasperreports.engine.*"%>
    <%@ page import="net.sf.jasperreports.engine.design.JasperDesign"%>
    <%@ page import="net.sf.jasperreports.engine.xml.JRXmlLoader"%>
    <%@ page import="net.sf.jasperreports.engine.export.*" %>
    <%@ page import ="net.sf.jasperreports.engine.*"%>
    <%@ page import ="net.sf.jasperreports.engine.JasperFillManager"%>
    <%@ page import ="net.sf.jasperreports.engine.JRException"%>
    <%@ page import="net.sf.jasperreports.engine.JasperReport"%>
    <%@ page import="net.sf.jasperreports.engine.JasperPrint"%>
    <html>
    <body bgcolor="00ffcc">
    <%
    try{
    Connection con = null;
    String url="jdbc:mysql://localhost/customer";
    String username = "root";
    String password = "cmsadmin";
    InputStream input=new FileInputStream(new File("C:/Documents and Settings/user/My Documents/NetBeansProjects/jasperreports/web/helloworld.xml"));
    JasperDesign design = JRXmlLoader.load(input);
    JasperReport report = JasperCompileManager.compileReport(design);
    Map params = new HashMap();
    params.put("reportTitle", "helloworld");
    params.put("author", "Muthu Kumar");
    params.put("startDate", (new java.util.Date()).toString());
    params.put("ReportTitle", "PDF JasperReport");
    <img class="emoticon" src="images/emoticons/confused.gif" border="0" alt="" />Class.forName("com.mysql.jdbc.Driver");<img class="emoticon" src="images/emoticons/confused.gif" border="0" alt="" /><img src="images/emoticons/confused.gif" border="0" alt="" />
    con = DriverManager.getConnection(url,username,password);
    JasperPrint print = JasperFillManager.fillReport(report, params, con);
    OutputStream output=new FileOutputStream(new File("C:/Documents and Settings/user/My Documents/NetBeansProjects/jasperreports/helloreportworld.pdf"));
    JasperExportManager.exportReportToPdfStream(print, output);
    // JasperViewer.viewReport(print);
    catch(SQLException es) {
    out.println(es);
    catch(JRException ex){
    //ex.printStackTrace();
    out.println(ex);
    %>
    </body>
    </html>The error it is saying is in the line Class.forName(....) ;
    Please look for the emoctions with question mark
    i DOn know what to do.
    Please help
    Im comparin the below JRXML file as with the above code
    <?xml version="1.0"?>
    <!DOCTYPE jasperReport
    PUBLIC "-//JasperReports//DTD Report Design//EN"
    "http://jasperreports.sourceforge.net/dtds/jasperreport.dtd">
    <jasperReport name="helloworld">
    <parameter name="reportTitle" class="java.lang.String"/>
    <parameter name="author" class="java.lang.String"/>
    <parameter name="startDate" class="java.lang.String"/>
    <queryString>
    <![CDATA[SELECT * FROM customer order by UserID ]]>
    </queryString>
    <field name="UserID" class="java.lang.String"/>
    <field name="UserName" class="java.lang.String"/>
    <field name="City" class="java.lang.String"/>
    <field name="State" class="java.lang.String"/>
    <title>
    <band height="60">
    <textField>
    <reportElement x="0" y="10" width="500" height="40"/>
    <textElement textAlignment="Center">
    <font size="24"/>
    </textElement>
    <textFieldExpression class="java.lang.String">
    <![CDATA[$P{reportTitle}]]>
    </textFieldExpression>
    </textField>
    <textField>
    <reportElement x="0" y="40" width="500" height="20"/>
    <textElement textAlignment="Center"/>
    <textFieldExpression class="java.lang.String">
    <![CDATA["Run by: " + $P{author}
    + " on " + $P{startDate}]]>
    </textFieldExpression>
    </textField>
    </band>
    </title>
    <columnHeader>
    <band height="30">
    <rectangle>
    <reportElement x="0" y="0" width="500" height="25"/>
    <graphicElement/>
    </rectangle>
    <staticText>
    <reportElement x="5" y="5" width="50" height="15"/>
    <textElement/>
    <text><![CDATA[UserID]]></text>
    </staticText>
    <staticText>
    <reportElement x="55" y="5" width="150" height="15"/>
    <text><![CDATA[UserName]]></text>
    </staticText>
    <staticText>
    <reportElement x="205" y="5" width="255" height="15"/>
    <text><![CDATA[City, State]]></text>
    </staticText>
    </band>
    </columnHeader>
    <detail>
    <band height="20">
    <textField>
    <reportElement x="5" y="0" width="50" height="15"/>
    <textElement/>
    <textFieldExpression class="java.lang.String">
    <![CDATA[$F{UserID}]]>
    </textFieldExpression>
    </textField>
    <textField>
    <reportElement x="55" y="0" width="150" height="15"/>
    <textElement/>
    <textFieldExpression class="java.lang.String">
    <![CDATA[$F{UserName}]]>
    </textFieldExpression>
    </textField>
    <textField>
    <reportElement x="205" y="0" width="255" height="15"/>
    <textElement/>
    <textFieldExpression class="java.lang.String">
    <![CDATA[$F{City} + ", " + $F{State}]]>
    </textFieldExpression>
    </textField>
    </band>
    </detail>
    </jasperReport>

    Glass_Fish wrote:
    I have set the classpath in the environment variables in the my computer properties.The web container has it's own properties. The "system" classpath means absolutely nothing to it. Read your server's documentation.

  • 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("").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.

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

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

  • Question about Class.forName()

    I am trying to get an instance of a class by its name. Now, I have tried both creating it with the class's actual name and with the class's name including the package path and both times I got a java.lang.ClassNotFoundException: my/package/MyClass.
    I am reading the name out of a properties file and that's working just fine according to my logging information btu here is the code anyway:
    Properties prop = new Properties();
    try{
         java.io.FileInputStream in = new java.io.FileInputStream(inv.getPath());
         prop.load(in);
         String temp = prop.getProperty("myclass1");
         Class c = Class.forName(temp);
         rollen.put("user",c.newInstance());
         temp = prop.getProperty("myclass2");
         c = Class.forName(temp);
         rollen.put("admin",c.newInstance());
    }catch(Exception e){
         //I'm doing some more logging here, guess that's not very interesting
    }I deleted all the logging info from this code snippet to make it shorter. But I can tell you that the name does get read out as my.package.MyClass - and the package and class name are correct...
    The entries in the properties files look like this:
    myclass1=my.package.MyClass
    myclass2=my.package.MyOtherClass
    Can you help me fix this, please?

    Is your classpath okay? I tried this:
    pkg\MyClass.javapackage pkg;
    public class MyClass {
        public MyClass () {
            System.out.println ("Woohoo!");
    }Test.javapublic class Test {
        public static void main (String[] parameters) throws Exception {
            Class.forName ("pkg.MyClass").newInstance ();
    }This outputsWoohoo!as expected.
    Kind regards,
      Levi

  • Class.forname (help please)

    Hello,
    I would like to load a class with class.forname. BUT, I just know the package and the path to the class. This class its not on class-path...
    What I know is:
    class: myClass
    package: org.java
    location: c:\myClases
    current class path: c:\myClassPath
    Class.forName("org.java.myClass");
    this above does not works because org.java.myClass its not on classpath
    Any ideas?

    URL directory = new URL("file:/location where your package is/"); // dont forget to end it with /
    URL[] classPath = new URL[] {directory};
    ClassLoader loader = URLClassLoader.newInstance(classPath);     
    Class youClass = Class.forName("org.java.myClass", true, loader);

  • Why use Class.forName() ?

    Why is it always adviced to use Class.forName( nameOfTheDriver ). Why dont we simply import the driver via the import statement ?
    Please note that this topic is part of a bigger topic I published in Java programming about difficulties I had importing driver. See:
    http://forums.java.sun.com/thread.jsp?forum=31&thread=147534
    for more details.

    Because using an import statement only tells the compiler about the driver. Class.forName() actually loads the driver when the program runs, which is what you want to happen.

  • How to create an object of our own class by using Class.forName()??

    how to create an object of our own class by using Class.forName()??
    plzz anser my qustion soon..

    Class.forName does not create an object. It returns a reference to the Class object that describes the metadata for the class in question--what methods and fields it has, etc.
    To create an object--regardless of whether it's your class or some other class--you could call newInstance on the Class object returned from Class.forName, BUT only if that class has a no-arg constructor that you want to call.
    Class<MyClass> clazz = Class.forName("com.mycompany.MyClass");
    MyClass mine = clazz.newInstance();If you want to use a constructor that takes parameters, you'll have to use java.lang.reflect.Constructor.
    Google for java reflection tutorial for more details.
    BUT reflection is often abused, and often employe when not needed. Why is it that you think you need this?

  • Strange use of Class.forName() in JDBC

    The following is the classical code to retreive data from a database via JDBC
            Connection con;
            Statement stmt;
            String querystring;
            String parametervalue = "";
            try {
                Class.forName("com.mysql.jdbc.Driver");
            } catch(java.lang.ClassNotFoundException e) {
                System.err.print("ClassNotFoundException: ");
                System.err.println(e.getMessage());
            try {
                con = DriverManager.getConnection(dburl);
                stmt = con.createStatement();
                querystring = "select ParameterValue from Profile ";
                ResultSet rs = stmt.executeQuery(querystring);
                if(rs.next()) parametervalue = rs.getString("ParameterValue");
                rs.close();
                stmt.close();
                con.close();
            } catch(SQLException ex) {
                System.err.println("-----SQLException-----");
                System.err.println("SQLState:  " + ex.getSQLState());
                System.err.println("Message:  " + ex.getMessage());
                System.err.println("Vendor:  " + ex.getErrorCode());
            return parametervalue;         but the use of Class.forName("com.mysql.jdbc.Driver") is strange. it doesn't need to get the returned Class
    like: Class t = Class.forName("com.mysql.jdbc.Driver"),and the DriverManager knows which driver to use!
    Any one can give an explanation?
    thanks

    * It's more natural from an OO perspective for me to
    tell the manager about the classes it manages thanfor
    the classes to know about the manager and tell it
    about themselves.
    No.Hmmm. Care to elaborate? I don't have anything to really back this up, but it seems to me that a class shouldn't have to know too much about the context in which it is used. Drivers shouldn't have to know that there is a DriverManager that will be managing them. IMHO.
    I thought of another reason: Since you're doing either the Class.forName or the DriverManger.register in the client, no work is saved there either way (as you said, register is just as easy to call as forName), but using Class.forName adds extra complexity in the Drivers. I guess this is probably the same as, or very close to "protected users from themselves" though.
    If the forName() doesn't happen somewhere then the
    class doesn't get loaded.I'm thinking more along the lines of classes getting loaded in a different area of the code than the DB client. Some kind of plugin-type thing maybe, where the plugin manager automatically loads all the classes in a certain classpath-like set of diretories and jars, without knowing or caring what each one is (DB plugin, graphics plugin, encryption plugin, messaging plugin, etc.) or how it's used. The DB client then wouldn't know which specific driver(s) it has available, only that whatever was visible to the plugin manager will be loaded, and some subset of that could be DB drivers.
    In this situation, it's not appropriate for the plugin manager to register the drivers, since it doesn't know anything about JDBC, and it's not appropriate for the DB client to register them, since it doesn't know what classes the plugin manager loaded.
    I suppose the DB client could query the plugin manager for all its loaded plugins, then check if each one implements Driver, and if it does, then register it. Or maybe the plugin manager could even store a map whose keys are interface Class objects or interface names and whose values are lists of the plugins that implement that interface.
    I don't know if this scenario is used, or is even good design, but it doesn't seem too farfetched. This is the kind of situation where it seems to me the driver is the one in the best position to know both a) he has been loaded and b) he needs to be registered.

  • Use of Class.forName() in JDBC

    Hi,
    I know that in JDBC "Class.forName()" is used to load the JDBC driver classes.
    Is this the only purpose of "Class.forName()" method specially in JDBC?

    thanks much..
    ok so. calling the Class.forName automatically
    creates an instance of a driver and registers it with
    the DriverManager.more or less
    When we use the string / string buffer class we don�t
    need to explicitly load the classes exist in
    �java.Lang� package.they get loaded - as do all classes - when your code first tries to use them.
    But to get the JDBC connection, we need to insert the
    code
    �Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");�..
    please clear my confusion.it's really because the JDBC driver might not be known at compile-time. Class.forName allows us to load classes at runtime we didn't know about at compile-time. you could just as easily load java.lang.String using the above method, but since the method takes a string, the class will be loaded already! you could also just as easily do
    import sun.jdbc.odbc.JdbcOdbcDriver;
    new JdbcOdbcDriver();that would also load the class. but that then couples your code to that particular driver. generally, in real applications, the driver classname would come from a config file, rather than hard-coded in the application. Class.forName() gives us that flexibility

  • Why class.forName to load driver

    hi all,
    as most of the times the loading of jdbc driver is carried out
    by using the function class.forName, Why so ?
    as i tryied with creating the object of the driver class like
    Object driver = new <JDBC DRIVER>;and the code worked fine
    so is there any difference in the two methods of loading the
    drivers ?
    if not wot is the use of method class.forname ?
    thanx

    That 's fine, but what if you change database back end in near future.
    I will define a property and used class.forName ("read property").
    In your case, you have to change the code about loading the JDBC driver as well.
    Using std. JDBC API functionality and loading driver dynamically, leaves some of the part of the code that are not a candidate for a change in case back-end DB is changed.
    BS

Maybe you are looking for

  • Java null pointer exception setting new preferences on a project

    Using thw Warehouse Builder Client 9.0.3 with Oracle 9i 9.0.1, I tried to change the Naming option on the Naming Tab to the "logical name mode". Then i pressed the Ok button and this caused a crash with a Java Null Pointer Exception. At this time, Al

  • Any word on a replacement for mavericks

    I'm wondering if anyone has heard any word about a replacement for Mavericks. Even after this long using it I still think it is a really poor os. If it were not such a chore I woud revert back to Mountain lion or Snow Leopard. 

  • Row Based Calculations - Pivot Table

    Hi, Can anyone help with creating calculating items in a pivot table. I have been following this example: http://obiee101.blogspot.com/2009/01/obiee-rowbased-calculations-in-pivot.html I have created a calculation item on the column of my pivot table

  • Multiple clients in DEV and QA for CHARM setup

    Blog /people/dolores.correa/blog/2008/07/26/first-steps-to-work-with-change-request-management-scenario is an excellence introduction to CHARM setup. However in real world, we have multiple clients on DEV and QAS systems. Could you help explain how t

  • ITunes window will not open

    I can play iTunes but the main window will not appear. It isn't minimized or hidden. The program is open and functioning, menus are there, Equalizer opens OK, but I just can't view any music (or the Visualizer UNLESS I'm in Full Screen mode under Vie