Class.forName() now working

Discussion in 'Plugin Development' started by V10lator, Mar 3, 2012.

Thread Status:
Not open for further replies.
  1. Hi,
    I'm trying to select a class dynamically, so I use Class.forName(). The problem is that I always get a ClassNotFoundException. :(

    let me try to explain the project setup a bit:
    Packages/Classes:
    Code:
    the.main.package
      - TheMain.class
    the.main.package.subpackage
      - AnAbstract.class
      - A.class
      - B.class
    A and B are extending AnAbstract, TheMain uses
    AnAbstract class = (AnAbstract)Class.forName("A");
    or
    AnAbstract class = (AnAbstract)Class.forName("B");
    and has the following import line:
    import the.main.package.subpackage.*

    BTW: I also tried it with all classes in the same package, but that didn't work, too. :(
     
  2. You need to include the package name in the lookup. The "import" lines only work on the compiler and not the runtime.
     
  3. Okay, sounds logical, but why isn't it working if all classes are in the same package and how exactly should I include them? Simply create an instance of them in the class constructor of the MainClass? That would destroy the dynamic a bit... :/

    //EDIT: Added this to the constructor of TheMain:
    new A();
    didn't change anything...
     
  4. Offline

    Shamebot

    He means Class.forName("the.main.package.subpackage.A");
     
  5. Yes this.
     
  6. Doesn't look right to me. You want to convert a Class<A> or Class<B> to "AnAbstract", that's different levels.
    Why don't you just do:
    Code:
    AnAbstract clazz = new A(...);
    (Same with B)
    Since A and B extend AnAbstract, the declaration works like that thanks to polymorphism.
    Or what exactly makes you need Class.forName(...)?
    If you need the Class instance, you can also just write "A.class" and "B.class"
     
  7. Cause I need dynamic class loading. As a workaround I used:
    Code:java
    1. Class<?> ac;
    2. if(string == gva[0])// No, that's not wrong. We really use == here for strings,
    3. ac = A.class;// cause it is the same instance and comparing the instances
    4. else// is faster than comparing the content.
    5. ac = B.class;

    Thanks, seems to work. :)
     
Thread Status:
Not open for further replies.

Share This Page