Query on Class.forName() method

What is the difference between instantiating using Class.forName() method and instantiating using the new operator?

You can do one of them at runtime.
For example:
public static void main(String[] args) {
   String className = args[0];
   Object o = Class.forName(className).newInstance();
}It's essentially a part of the reflection API which is generally used when you don't know exactly what you want to manipulate at compile time.

Similar Messages

  • Query in Class and Method

    Hi all,
            I have a requirement which requires me to get the value enterd on the PCUI screen. Can anyone please tell me how to get the value entered on the screen .
    Kindly reply immediately as it is bit urgent.
    Regards,
    Vijay

    Did you solve your problem ?
    I have posted similar question recently. Please guide me if you found any solution.
    Vallabh.

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

  • 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

  • For class.forName()

    Class.forName()
    method is used in DataBase Connection
    we cannot trap the returned value why n how it works in DataBase Connection

    Class.forName()
    method is used in DataBase Connection
    we cannot trap the returned value why n how it works
    in DataBase ConnectionYes, you can "trap" the returned value, but you don't need to. This call loads the driver class. For all JDBC drivers it is mandatory to have a static initializer that registers the driver at the DriverManager, so loading the class is all you need to do in order to make it known to JDBC.

  • Database connectivity without using Class.forName()

    Hi,
    Can anyone please tell how we can connect to a database without in java without using the Class.forName() method , and then how the database driver gets loaded.
    Regards,
    Tanmoy

    Hi,
    I recently wrote code that connects to a database without using Class.forName() in order to be compatible with Microsoft's JVM. I read about it here:
    http://www.idssoftware.com/faq-e.html#E1
    Basically, you create a new Driver object and use its connect method.
    Here's what my particular code ended up being:
    String url = "jdbc:mysql://localhost:3306/test?user=root&password=mypass";
    Driver drv = new org.gjt.mm.mysql.Driver();
    Connection con = drv.connect(url,null);

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

  • ForName method

    what is the main purpuse of class.forName() method.
    pls give me the detailed discription.

    What's wrong with [this detailed description|http://java.sun.com/javase/6/docs/api/java/lang/Class.html#forName(java.lang.String)]?

  • Instantiating object using Class.forName()

    What is the difference between instantiating using Class.forName() method and instantiating using the new operator?

    The difference is that you can use the new operator to instantiate an object, but you can't do it using Class.forName().
    But seriously folks...
    Presumably you're talking about Class.newInstance()--which often appears right on the heels of Class.forName().
    New gives you compile-time checks you don't get with Class.forName(). If it compiles with new, then you know the constructor in question exists on the class in question.
    With Class.newInstance() (and it's cousin (also called newInstance, I think) in the Constructor class), you can't be sure until you actually execute it whether that constructor even exists.
    New requires you to know the class at compile time. NewInstance lets you defer the specific class until runtime.
    New is simpler and more direct.
    (Did I just do your homwork for you? Hope not.)

  • Detecting static calls in methods via Class.forName(...)

    Hi!
    I'm trying to detect, if a method (or a contructor) of a Class object, loaded by Class.forName(...) contains a static call like System.out.println( "some text" );
    I need it to figure out if (in this case above) the class "System" is needed for running this example class.
    I don't have the source code (and don't want it anyway) to write a parser for it. I just want to extract this single information: Is there a method/contructor in the given class containing static calls by any other classes and what's the the of these classes?
    Anybody an idea?
    Thoto

    I'm trying to detect, if a method (or acontructor)
    of a Class object, loaded by Class.forName(...)
    contains a static call like System.out.println("some
    text" );BCEL should be able to do this.But I need to do that in my own program.
    System.out.println() is not a static method.That's right. If it's static or not doesn't really matter, it's just the information WHICH class is embedded into this call. It could also be a call like
    int i = Integer.MAX_VALUE.I just need (in that case) the informatation that the class "Integer" is needed to proceed that call.
    You can use javap to find this, or the BCEL library.I already did that with javap. But it's useless for me, I need it in my own program. I don't want to decompile some program. I have no illegal intentions in hacking or so. It's for my own programs, but I don't want to scan the source code.
    Unless this is homework, why would you want to know
    this information?That sounds, like you know the answer, but can't tell me, because it's the most important treasure in the world and THEY will kill you if you tell others... :-)
    No, it's not a homework and I don't want any source code from you, I'm a curious guy.

  • Error while executing query on portal-SAPMSSY1 method : UNCAUGHT_EXCEPTION

    Hello all,
    I have created a quey and executed it on portal and everything just works fine. The query has few input varaibles at the start like fiscal year and some other inputs. I saved the query in my Portal favorites and then when I try to excute it from there it gives me a runtime BI error.
    Termination message sent ABEND RSBOLAP (000): Program error in class SAPMSSY1 method : UNCAUGHT_EXCEPTION  MSGV1: SAPMSSY1  MSGV3: UNCAUGHT_EXCEPTION
    I guess it errors out because of the variable input part at the start of query.
    We already have note "950992" in the system so wonder what next now.
    Any inputs appreciated.
    Thanks,
    Kiran

    We are having the same issue too - we are SP13. Our query is built on a Infoset, and the problem comes with 0FISCPER variable, when we try to do a input help (F4) in Bex. this happens only when I use fiscper on queries bulit on INFOSETS, and it works perfectly alright with all other cubes.
    <i>System error in program CL_RSMD_RS_SPECIAL and form
    IF_RSMD_RS~READ_META_DATA-02 (see long text)
        Message no. BRAIN299
    Diagnosis
        This internal error is an intended termination resulting from a program
        state that is not permitted.
    Procedure
        Analyze the situation and inform SAP.
        If the termination occurred when you executed a query or Web template,
        or during interaction in the planning modeler, and if you can reproduce
        this termination, record a trace (transaction RSTT).</i>
        For more information about recording a trace, see the documentation for
        the trace tool environment as well as SAP Note 899572.
    and in portal, it gets to the point of variable screen and then throws a error msg.
    <i>ABEND RSBOLAP (000): Program error in class SAPMSSY1 method : UNCAUGHT_EXCEPTION
      MSGV1: SAPMSSY1
      MSGV3: UNCAUGHT_EXCEPTION</i>
    Message was edited by:
            voodi
    Message was edited by:
            voodi

  • Calling a class's method from another class

    Hi, i would like to know if it's possible to call a Class's method and get it's return from another Class. This first Class doesn't extend the second. I've got a Choice on this first class and depending on what is selected, i want to draw a image on the second class witch is a Panel extended. I put the control "if" on the paint() method of the second class witch is called from the first by the repaint() (first_class.repaint()) on itemStateChanged(). Thankx 4 your help. I'm stuck with this.This program is for my postgraduation final project and i'm very late....

    import java.awt.*;
    import java.sql.*;
    * This type was generated by a SmartGuide.
    class Test extends Frame {
         private java.awt.Panel ivjComboPane = null;
         private java.awt.Panel ivjContentsPane = null;
         IvjEventHandler ivjEventHandler = new IvjEventHandler();
         private Combobox ivjCombobox1 = null;
    class IvjEventHandler implements java.awt.event.WindowListener {
              public void windowActivated(java.awt.event.WindowEvent e) {};
              public void windowClosed(java.awt.event.WindowEvent e) {};
              public void windowClosing(java.awt.event.WindowEvent e) {
                   if (e.getSource() == Test.this)
                        connEtoC1(e);
              public void windowDeactivated(java.awt.event.WindowEvent e) {};
              public void windowDeiconified(java.awt.event.WindowEvent e) {};
              public void windowIconified(java.awt.event.WindowEvent e) {};
              public void windowOpened(java.awt.event.WindowEvent e) {};
         private Panel ivjPanel1 = null;
    * Combo constructor comment.
    public Test() {
         super();
         initialize();
    * Combo constructor comment.
    * @param title java.lang.String
    public Test(String title) {
         super(title);
    * Insert the method's description here.
    * Creation date: (11/16/2001 7:48:51 PM)
    * @param s java.lang.String
    public void conexao(String s) {
         try {
              Class.forName("oracle.jdbc.driver.OracleDriver");
              String url = "jdbc:oracle:thin:system/[email protected]:1521:puc";
              Connection db = DriverManager.getConnection(url);
              //String sql_str = "SELECT * FROM referencia";
              Statement sq_stmt = db.createStatement();
              ResultSet rs = sq_stmt.executeQuery(s);
              ivjCombobox1.addItem("");
              while (rs.next()) {
                   String dt = rs.getString(1);
                   ivjCombobox1.addItem(dt);
              db.close();
         } catch (SQLException e) {
              System.out.println("Erro sql" + e);
         } catch (ClassNotFoundException cnf) {
    * connEtoC1: (Combo.window.windowClosing(java.awt.event.WindowEvent) --> Combo.dispose()V)
    * @param arg1 java.awt.event.WindowEvent
    /* WARNING: THIS METHOD WILL BE REGENERATED. */
    private void connEtoC1(java.awt.event.WindowEvent arg1) {
         try {
              // user code begin {1}
              // user code end
              this.dispose();
              // user code begin {2}
              // user code end
         } catch (java.lang.Throwable ivjExc) {
              // user code begin {3}
              // user code end
              handleException(ivjExc);
    * Return the Combobox1 property value.
    * @return Combobox
    /* WARNING: THIS METHOD WILL BE REGENERATED. */
    private Combobox getCombobox1() {
         if (ivjCombobox1 == null) {
              try {
                   ivjCombobox1 = new Combobox();
                   ivjCombobox1.setName("Combobox1");
                   ivjCombobox1.setLocation(30, 30);
                   // user code begin {1}
                   this.conexao("select * from referencia");
                   // user code end
              } catch (java.lang.Throwable ivjExc) {
                   // user code begin {2}
                   // user code end
                   handleException(ivjExc);
         return ivjCombobox1;
    * Return the ComboPane property value.
    * @return java.awt.Panel
    /* WARNING: THIS METHOD WILL BE REGENERATED. */
    private java.awt.Panel getComboPane() {
         if (ivjComboPane == null) {
              try {
                   ivjComboPane = new java.awt.Panel();
                   ivjComboPane.setName("ComboPane");
                   ivjComboPane.setLayout(null);
                   getComboPane().add(getCombobox1(), getCombobox1().getName());
                   getComboPane().add(getPanel1(), getPanel1().getName());
                   // user code begin {1}
                   // user code end
              } catch (java.lang.Throwable ivjExc) {
                   // user code begin {2}
                   // user code end
                   handleException(ivjExc);
         return ivjComboPane;
    * Return the ContentsPane property value.
    * @return java.awt.Panel
    /* WARNING: THIS METHOD WILL BE REGENERATED. */
    private java.awt.Panel getContentsPane() {
         if (ivjContentsPane == null) {
              try {
                   ivjContentsPane = new java.awt.Panel();
                   ivjContentsPane.setName("ContentsPane");
                   ivjContentsPane.setLayout(new java.awt.BorderLayout());
                   getContentsPane().add(getComboPane(), "Center");
                   // user code begin {1}
                   // user code end
              } catch (java.lang.Throwable ivjExc) {
                   // user code begin {2}
                   // user code end
                   handleException(ivjExc);
         return ivjContentsPane;
    * Return the Panel1 property value.
    * @return Panel
    /* WARNING: THIS METHOD WILL BE REGENERATED. */
    private Panel getPanel1() {
         if (ivjPanel1 == null) {
              try {
                   ivjPanel1 = new Panel();
                   ivjPanel1.setName("Panel1");
                   ivjPanel1.setBackground(java.awt.SystemColor.scrollbar);
                   ivjPanel1.setBounds(24, 118, 244, 154);
                   // user code begin {1}
                   // user code end
              } catch (java.lang.Throwable ivjExc) {
                   // user code begin {2}
                   // user code end
                   handleException(ivjExc);
         return ivjPanel1;
    * Called whenever the part throws an exception.
    * @param exception java.lang.Throwable
    private void handleException(java.lang.Throwable exception) {
         /* Uncomment the following lines to print uncaught exceptions to stdout */
         // System.out.println("--------- UNCAUGHT EXCEPTION ---------");
         // exception.printStackTrace(System.out);
    * Initializes connections
    * @exception java.lang.Exception The exception description.
    /* WARNING: THIS METHOD WILL BE REGENERATED. */
    private void initConnections() throws java.lang.Exception {
         // user code begin {1}
         // user code end
         this.addWindowListener(ivjEventHandler);
    * Initialize the class.
    /* WARNING: THIS METHOD WILL BE REGENERATED. */
    private void initialize() {
         try {
              // user code begin {1}
              // user code end
              setName("Combo");
              setLayout(new java.awt.BorderLayout());
              setSize(460, 300);
              setTitle("Combo");
              add(getContentsPane(), "Center");
              initConnections();
         } catch (java.lang.Throwable ivjExc) {
              handleException(ivjExc);
         // user code begin {2}
         // user code end
    * Insert the method's description here.
    * Creation date: (11/17/2001 2:02:58 PM)
    * @return java.lang.String
    public String readCombo() {
         String dado = ivjCombobox1.getSelectedItem();
         return dado;
    * Starts the application.
    * @param args an array of command-line arguments
    public static void main(java.lang.String[] args) {
         try {
              /* Create the frame */
              Test aTest = new Test();
              /* Add a windowListener for the windowClosedEvent */
              aTest.addWindowListener(new java.awt.event.WindowAdapter() {
                   public void windowClosed(java.awt.event.WindowEvent e) {
                        System.exit(0);
              aTest.setVisible(true);
         } catch (Throwable exception) {
              System.err.println("Exception occurred in main() of Test");
              exception.printStackTrace(System.out);
    * Insert the type's description here.
    * Creation date: (11/17/2001 1:59:15 PM)
    * @author:
    class Combobox extends java.awt.Choice {
         public java.lang.String dado;
    * Combobox constructor comment.
    public Combobox() {
         super();
         initialize();
    * Called whenever the part throws an exception.
    * @param exception java.lang.Throwable
    private void handleException(java.lang.Throwable exception) {
         /* Uncomment the following lines to print uncaught exceptions to stdout */
         // System.out.println("--------- UNCAUGHT EXCEPTION ---------");
         // exception.printStackTrace(System.out);
    * Initialize the class.
    /* WARNING: THIS METHOD WILL BE REGENERATED. */
    private void initialize() {
         try {
              // user code begin {1}
              // user code end
              setName("Combobox");
              setSize(133, 23);
         } catch (java.lang.Throwable ivjExc) {
              handleException(ivjExc);
         // user code begin {2}
         // user code end
    * main entrypoint - starts the part when it is run as an application
    * @param args java.lang.String[]
    public static void main(java.lang.String[] args) {
         try {
              java.awt.Frame frame = new java.awt.Frame();
              Combobox aCombobox;
              aCombobox = new Combobox();
              frame.add("Center", aCombobox);
              frame.setSize(aCombobox.getSize());
              frame.addWindowListener(new java.awt.event.WindowAdapter() {
                   public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
              frame.setVisible(true);
         } catch (Throwable exception) {
              System.err.println("Exception occurred in main() of Combobox");
              exception.printStackTrace(System.out);
    * Insert the type's description here.
    * Creation date: (11/17/2001 2:16:11 PM)
    * @author:
    class Panel extends java.awt.Panel {
    * Panel constructor comment.
    public Panel() {
         super();
         initialize();
    * Panel constructor comment.
    * @param layout java.awt.LayoutManager
    public Panel(java.awt.LayoutManager layout) {
         super(layout);
    * Called whenever the part throws an exception.
    * @param exception java.lang.Throwable
    private void handleException(java.lang.Throwable exception) {
         /* Uncomment the following lines to print uncaught exceptions to stdout */
         // System.out.println("--------- UNCAUGHT EXCEPTION ---------");
         // exception.printStackTrace(System.out);
    * Initialize the class.
    /* WARNING: THIS METHOD WILL BE REGENERATED. */
    private void initialize() {
         try {
              // user code begin {1}
              // user code end
              setName("Panel");
              setLayout(null);
              setSize(260, 127);
         } catch (java.lang.Throwable ivjExc) {
              handleException(ivjExc);
         // user code begin {2}
         // user code end
    * main entrypoint - starts the part when it is run as an application
    * @param args java.lang.String[]
    public static void main(java.lang.String[] args) {
         try {
              java.awt.Frame frame = new java.awt.Frame();
              Panel aPanel;
              aPanel = new Panel();
              frame.add("Center", aPanel);
              frame.setSize(aPanel.getSize());
              frame.addWindowListener(new java.awt.event.WindowAdapter() {
                   public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
              frame.setVisible(true);
         } catch (Throwable exception) {
              System.err.println("Exception occurred in main() of java.awt.Panel");
              exception.printStackTrace(System.out);
    * Insert the method's description here.
    * Creation date: (11/17/2001 2:18:36 PM)
    public void paint(Graphics g) {
    /* Here's the error:
    C:\Test.java:389: non-static method readCombo() cannot be referenced from a static context
         System.out.println(Test.lerCombo());*/
         System.out.println(Test.readCombo());

  • 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

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

Maybe you are looking for

  • Not understandable message, no sender found..

    Hi guys! I have trobles with my IDoc -> SOAP scenario.. I have configured all needed objects and when I run scenario test, I get error in german: Die nachricht ist unvollstaendig. Es wurde kein sender gefunden. (<a href="http://jarunek.host.sk/sap/er

  • I have cookies enabled but I keep getting the "enable cookies" message when signing into Gmail.

    I cannot sign in to my Gmail account through Firefox. I am getting the message:Your browser's cookie functionality is turned off. Please turn it on. [?] When I go in the cookies ARE enabled. I have cleared out all the cookies and tried to open Gmail

  • Help;;;;;cant select calendar when creating inventory organization parameters

    hello there i am trying to define a new inventory organization. i have created inventory organization. i opened organization parameters and in the inventory parameters tab, when i tried to enter calendar, it is saying list of values has no entries. i

  • Delete Request

    I have written a routine to delete request from a cube. This routine is written in the "Delete Overlapping Request" object of the process chain and included in the Data selection field. But the program gives the error "ABAP/4 : BCD_OVERFLOW" error. I

  • Combining image and text in accordion content panel

    Hello, I'm having difficulty displaying image and text together within an accordion content panel.  What I need is a thumbnail photo of a staff member plus a short bio.  I've put a panel together so it displays as needed in Live View, but not in IE8,