Class.forName().newInstance(): InstantiationException for subclass

I use classes not known at compile time. So far, these classes implemented an interface and I instantiated via
final MyInterface fd = (MyInterface) clazz.newInstance();and this worked fine. Now, an interface is not enough anymore and those classes need to subclass a new superclass. For compatibility, I let my new super class also implement the old interface "MyInterface", but the code above doesn't work anymore as it throws a
java.lang.InstantiationException: one.two.Julia$1
     at java.lang.Class.newInstance0(Class.java:340)
     at java.lang.Class.newInstance(Class.java:308)This looks like some inner class, but none of these classes have any inner classes - they are rather simple classes with no constructors and no other superclass/interface.
I also tried to cast to the new superclass, but with no success. What could be the problem? (Inserting explicitaly an empty constructor didn't help either). Also tried deleting all classes; restart IDE/computer; ...
If I simple switch back for the classes to only implement the interface, it works again.

Thrown when an application tries to create an instance of a class using the newInstance method in class Class, but the specified class object cannot be instantiated because it is an interface or is an abstract class.
1) Print out clazz.getClassName() right before calling newInstance.
2) Post the code for whatever class getClassName() returns.

Similar Messages

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

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

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

  • Class.forName() lookup places for the driver

    I'm trying to use java with mysql through mysql-connector-java all of them installed in Linux Debian Lenny, I've already read all the docs related to each of them, and they are workling except for one thing, It seems that jdk can't find the CLASSPATH value, so If I want to use the jar file of mysql-connector I have to do it like:
    java -cp /connector myprogramSo, my question is: In linux OS, where - I mean in what file(s)- do jdk search the definition of CLASSPATH var?
    At this time I've already set the CLASSPATH in .bashrc (from my HOME directory) and in /etc/profile and in both case jdk can't find it.
    Regards

    Yes you will always need to add your jar dependencies to your classpath. That's true of any jar files, not just database drivers.
    Let's suppose your driver is named "mysql-connector-java-bin.jar"
    When I worked in the command line mode on Linux, to compile programs I made use of the command line argument files ... described here...
    http://java.sun.com/j2se/1.5.0/docs/tooldocs/solaris/javac.html#commandlineargfile
    Then when I wanted to run a program, I wrote a bash script that contained all the classpath information
    -- begin script --
    #!/bin/bash
    # Run myprogram
    java -cp {directory of jar file}/my-connector-java-bin.jar myprogram
    -- end script --
    then save the file as Runit.sh or something. Then in command line you can just call bash Runit.sh without typing out the full directory path of the database jar each time you run your application.
    The value for {directory of jar file} must either be an absolute value from the root of the filesystem or relative to the current working directory. If it's relative to the current working directory use "./" as the prefix.
    In general, it's best not to rely on system settings, like /etc/profile entries, for your classpath.

  • Can Class.forName("SomeClassName").newInstance() work in all classes?

    I saw some classes don't have a method called "newInstance()".
    but I have seen some advices say that is better using "Class.forName().newInstance()" than using "Class.forName()".

    I saw some classes don't have a method called
    "newInstance()".If you have class Foo, and you do Class.forName("Foo").newInstance();you're not calling Foo's newInstance method. You're calling java.lang.Class' newInstance method. You have a Class object that represents the Foo class. You tell that Class object newInstance() which invokes the public no-arg constructor of class Foo (as if you had done new Foo()). If Foo doesn't have a public no-arg constructor, you'll get an exception.
    but I have seen some advices say that is better using
    "Class.forName().newInstance()" than using
    "Class.forName()".They do two completely different things, and Class.forName().newInstance() first does Class.forName() and then class newInstance() on what that returns.
    Class.forName("Foo") returns the Class object that is associated with class Foo. It also loads the class if it hasn't already been loaded. It returns an instance of java.lang.class
    newInstance() calls the public, no-arg ctor of that class, if that ctor exists. Otherwise it throws an exeption. If it succeeds, it returns an instance of Foo.

  • Need a clear explanation for class.forName()

    Class.forName(sun.jdbc.odbc.JdbcOdbcDriver);
    Connection conn = DriverManager.getConnection("aadsn","xxxxx","xxxx");
    actually what it does behind the scene.

    (Copied from http://forum.java.sun.com/thread.jsp?forum=48&thread=471358)
    Class.forName() loads the given class. In itself, that isn't interesting. The beef lies in that loading a class executes any static blocks in that class.
    If you had the source to com.mysql.jdbc.Driver, it would probably start something like:
    public class Driver
        static {
            Driver driver_object = new Driver();
            java.sql.DriverManager.registerDriver(driver_object);
    }The static block does the actual work of registering the driver. Class.forName() is really just a bit of a hack to get that static block executed.
    The newInstance() call is customary because there is an old rumor that some buggy JDBC driver somewhere is missing the static block, and has the registerDriver() call in a Driver() object constructor instead. A belt and suspenders kind of thing.
    If you want to see real life examples of that static block, google around for open source JDBC drivers.

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

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

  • Class.forName("com.proj.someclass").newInstance()

    This works fine if "someclass" is in classpath but doesn't work if "someclass" is in jar file. How to make it work with classes packed into jar?

    Hi Mike.
    I think you need to write your own customized ClassLoader. Haven't done it myself, but I know the question has been up before, and ansered, and problem solved... Do some search. And maybee you coud be more specific about what you want to achive. Is this an applet or an application? And why do you need to use Class.forName? And why do you want the class to be in a .jar file?
    Ragnvald Barth
    Software enigneer

  • How can create the object ? Via class.forName

    Hi,
    i want to create the object via class.forname?........
    i have tryed like this Class obj=Class.forName("sample.Employee");
    but it gives error like this......
    java.lang.InstantiationException: sample.Employee
         at java.lang.Class.newInstance0(Class.java:291)
         at java.lang.Class.newInstance(Class.java:259)
         at sample.ArrayListTest.main(ArrayListTest.java:22)

    The line
    Class obj=Class.forName("sample.Employee");does NOT create a new object of class
    sample.Employee. It only loads the class and creates
    the Class object. You have to call newInstance() to
    create a new instance of the class:
    Object obj =
    Class.forName("sample.Employee").newInstance();I guess you already did something like that, because
    forName() itself doesn't throw an
    InstantiationException.
    For this to work, class sample.Employee must be in
    the classpath and it must have a public constructor
    that takes no arguments.this is my full code it dosn't work i don,t know
    public class ArrayListTest {
    public ArrayListTest() {  }
    public static void main(String[] args) {
    ArrayList employees = new ArrayList();
    // create some employees
    /* Employee employee_1 = new Employee("John", 2000);
    Employee employee_2 = new Employee("Carl", 3000);
    Employee employee_3 = new Employee("Ron", 4000);*/
    /*instead of this Employee employee_1 i want to create the new obeject by using*/
    try{
    Object obj = Class.forName("sample.Employee").newInstance();
    catch(Exception e)
    e.printStackTrace();
    // add them to your list
    //employees.add(employee_1);
    //employees.add(employee_2);
    //employees.add(employee_3);
    // display only the names your list
    for(int j = 0; j < employees.size(); j++) {
    Employee temp = (Employee)employees.get(j);
    System.out.println("nr. "+(j+1)+": "+temp.getName()+"\nnr. "+(j+1)+": "+temp.getSalary());
    // invoke the toString()-method from Employee
    for(int j = 0; j < employees.size(); j++) {
    Employee temp = (Employee)employees.get(j);
    System.out.println(temp.toString());
    } // class ArrayListTest
    again the same error occur................

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

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

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

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

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

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

Maybe you are looking for

  • Jam Pack: Symphony Orchestra not working on new iMac with Maverick

    Hi, i received my new iMac 27 inch Haswell with Maverick installed. I migrated most of the stuff i need but it seems the Symphony Orchestra Jam Pack instruments weren't migrated to Garageband. Now i read somehwere that this JamPack doesn't work on Ma

  • Dell 3007 problem

    Hey, Anyone know if I have to do anything special to get the Dell Ultrasharp 3007 to work with my G5? The highest resolution I can choose is 1280x800. Seems odd. I am at my work computer and the it is a 2.5 Dual, with ATI Radeon 9800 XT. The first gu

  • Deauthorizing a computer without access to it

    I am trying to deauthorize my recent exboyfriend's computer. Clearly, I do not have access to it. I do not want to authorize 5 computers in order to deauthorize one. Any suggestions???

  • Printing smartform

    Hi All,   My requirement is to convert the smartform to PDF and print it simulteneously. I'm using the fm <b>convert_otf_2_pdf</b> to convert the smartform into PDF. How can I print the smartform soon after converting it to PDF format?

  • When will Oracle JDeveloper 11.1.1.4 (weblogic 10.1.4) be available?

    Hi, during last month a lot of interim patches for jdev and wls was released. When can we get a fully regression tested version including all last patches? Ciao André