Dynamic Class Instantiation with getDefinitionByName

Ok so I am trying to follow the following example in
instantiating a class dynamically:
http://nondocs.blogspot.com/2007/04/flexhowtoinstantiate-class-from-class.html
My AS3 code looks like this:
var myClassName:String = event.templateName;
//Alert.show(getDefinitionByName(myClassName).toString());
try {
var ClassReference:Class = getDefinitionByName(myClassName)
as Class;
var myInstanceObject:* = new ClassReference();
} catch( e:Error ) {
Alert.show("Could not instantiate the class " + myClassName
+ ". Please ensure that the class name is a valid name and that the
Actionscript 3 class or MXML file exists within the project
parameters.");
return;
However I get an error: ReferenceError: Error #1065: Variable
OrderEdit is not defined.
The problem is that my class is located in an altogether
different project directory from the the calling main project (I
include this project with these classes I am trying to dynamically
instantiate in the project source path).
Every example I have seen so far involves some sort of hard
coding. I am builidng a plugin/component that I intend to use in
various places in my site and have any general hard code is
UNACCEPTABLE. How can I make this process COMPLETELY HARD CODE
FREE??
Thanks a ton!

I am also facing the same problem, I have imported swc (flash
created) to flex library path (Flex project >> properties
>> Flex build path >> Library path >> add swc)
These swc files are icons for my applications with some
scripts (written in flash, I am using UIMovieClip). So I want to
make it dynamic.
I write a xml with these component name and want to create a
object and then add that object to my canvas according to xml data.
if I code like this:
var myIcon:IconA = new IconA()
canvas.addChild(myIcon); //canvas is instance of Canvas
then its working, but if I code like
var myDynClass:Class = getDefinitionByName("IconA") as Class
var myIcon:* = new myDynClass()
canvas.addChild(myIcon); //canvas is instance of Canvas
Then its showing me same error
Error
Error #1065: Variable IconA is not defined.
So, I have seen your reply but didn't get it, how can I fix
this problem using modules. or any other way...
Thanks,

Similar Messages

  • Can I do dynamic class cast with java SE1.4.2?

    Hi,
    I have some question on dynamic class cast.
    I'm using java SE1.4.2. Suppose I have a method :
    castObjectToSomething(Object o)
    Something s = (Something) o;
    However, I don't know what is the class to cast until runtime. How can I do a runtime class cast?
    I know that java 5.0 have a Class.cast() method which java1.4.2 does not have. But can I do the same stuff by using SE1.4.2?
    Thank You!!!!!
    oh_silly

    There is no sense in wanting to cast to a class that is only known at runtime. Because you can't do anything with such a class during runtime. Even though you could technically retrieve the class name, the method names and the parameter names, you could do nothing with this class as you don't know what it is doing. If you would know what it can do, you would know it also during compile time and then you would know the classname/interface name you want to cast to and can import it and use it reasonably.
    Tell us the requirement that you think you have and we will proof you that you don't need such a requirement.

  • Question  about dynamic class loading with thread built in

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

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

  • Dynamic class loading with Webstart

    Hello !
    //within the jar-file at the webstart-directory
    public interface MyFrame{
    public void createFrame();
    //within the jar-file dynamically downloaded
    public class MyExtFrame extends JFrame implements MyFrame{
    String className = "MyExtFrame";
    ClassLoader cl = ClassLoader.getSystemClassLoader();
    JarClassLoader jarLoader = new JarClassLoader (cl, jarFile));
    /* Load the class from the jar file and resolve it. */
    Class c = jarLoader.loadClass (className, true);
    /* Create an instance of the class.
    Object o = c.newInstance();
    /* Are we using a class we specifically know about? */
    if (o instanceof MyFrame){
    // Yep, lets call a method we know about. */
    MyFrame client=(MyFrame) o;
    //call a class-method (here creates the whole gui-object at once)
    client.createFrame();
    This is the code i'm using and i've encountered following problem, if i put this code into an application without webstart, anything works fine, but with webstart i'll get a: java.lang.NoClassDefFoundError
    Then i've put the MyFrame-classes into the downloaded jar-file, but this won't work either, i'll get a ClassCastException.
    What do i have to do, to become it working ?
    Thanks for any conclusions and help.
    Michael

    Finally i've found out myself, i've read some postings in this forum and put them all together, so that my webstart-application finally works the way i want...
    That was the topic:
    Downloading a jar-file and starting a class from this jar-file within a webstart application (dynamic class loading).
    I'll post my final solution for this problem, may be it would be useful in future for anyone else.
    //grant all permissions on the clientside
    Policy.setPolicy( new Policy() {
    public PermissionCollection getPermissions(CodeSource codesource) {
    Permissions perms = new Permissions();
    perms.add(new AllPermission());
    return(perms);
    public void refresh(){
    //get the current classloader
    ClassLoader cl = MyLoadedClass.class.getClassLoader();
    //create a new url-classloader while using the current classloader
    URL[] urls = new URL[1];
    File f = new File(new String(jarName));
    urls[0] = f.toURL();
    URLClassLoader ul = new URLClassLoader(urls, cl);
    //load a class from jarfile
    Class c = ul.loadClass(new String(className));
    //get an object from loaded class
    Object o = c.newInstance();
    /* Are we using a class we specifically know about? */
    if (o instanceof KnownInterface){
    // Yep, lets call a method we know about. */
    KnownInterface client = (KnownInterface) o;
    client.doAnything();

  • Dynamic Class Loading with interface

    Hello
    I would appreciate any help on the following problem.
    I need to load all classes in a particular directory and its subdirectories (top directory is known but not in the classpath) which implement a predefined interface. At the moment I am using a lot of reflection to accomplish this and believe it can be avoided somehow using the fact that I know these classes have to implement a predefined interface.
    At the moment, I am searching through the directory and subdirectory, loading all names of classes into a vector using a custom URLClassloader, and then load all classes in the vector into modulecontainers to populate a defaultmutabletree which is displayed on the gui.
    I'm sure that knowing the interface means there's a more straightforward way.
    Thanks in advance.

    Finally i've found out myself, i've read some postings in this forum and put them all together, so that my webstart-application finally works the way i want...
    That was the topic:
    Downloading a jar-file and starting a class from this jar-file within a webstart application (dynamic class loading).
    I'll post my final solution for this problem, may be it would be useful in future for anyone else.
    //grant all permissions on the clientside
    Policy.setPolicy( new Policy() {
    public PermissionCollection getPermissions(CodeSource codesource) {
    Permissions perms = new Permissions();
    perms.add(new AllPermission());
    return(perms);
    public void refresh(){
    //get the current classloader
    ClassLoader cl = MyLoadedClass.class.getClassLoader();
    //create a new url-classloader while using the current classloader
    URL[] urls = new URL[1];
    File f = new File(new String(jarName));
    urls[0] = f.toURL();
    URLClassLoader ul = new URLClassLoader(urls, cl);
    //load a class from jarfile
    Class c = ul.loadClass(new String(className));
    //get an object from loaded class
    Object o = c.newInstance();
    /* Are we using a class we specifically know about? */
    if (o instanceof KnownInterface){
    // Yep, lets call a method we know about. */
    KnownInterface client = (KnownInterface) o;
    client.doAnything();

  • AS3 - dynamic class names with *new* operator

    I'm using AcrtionScript 3 and Adobe Flash 9 Public Alpha.
    I have 50 movie clips in the Library that use Linkage to set
    the Class name to: Img1, Img2, Img3, ..., Img50.
    I have a parent class named RandImg. I want the constructor
    for RandImg to randomly select one of the 50 movie clips from the
    Library and display it. I could get this working by generating a
    random number, and then writing a really huge switch statement to
    associate each possible random number with its respective Library
    Movie Clip Class name, but I would much rather do this with a
    dynamic/variable class name based on the random number, such as:
    var nImgChoice:Number = Math.floor( Math.random( ) * 50 ) +
    1;
    var mcImg:MovieClip = new [ "Img"+String(nImgChoice) ] ( );
    addChild( mcImg );
    Note that this used to be possible in AS 2 by doing the
    following:
    this.attachMovie( "Img"+String(nImgChoice) , "mcImg",
    this.getNextHighestDepth());
    Suggestions?
    Thanks,
    ~JC

    import flash.display.DisplayObject;
    import flash.display.Sprite;
    import flash.utils.getDefinitionByName;
    var nImgChoice:Number = Math.floor( Math.random( ) * 50 ) +
    1;
    var ClassReference:Class =
    getDefinitionByName("Img"+String(nImgChoice) ) as
    Class;
    var instance:Object = new ClassReference();
    addChild(DisplayObject(instance));

  • Dynamic Class Instantiating

    Hi,
    I need to dynamicaly instantiate classes at runtime, that is multiple instances, with different reference variables.
    I can easily intantiate a number of classes with different object variables, but i need to do it dynamically at runtime. anyone?

    I think u can better solve this by using Hashtable like data-structure.
    The key will be a String(external data like phone no.-as u said).
    The value will be the actual object which u r trying to load dynamically.
    u can load the class dynamically as follows.
    Class className=Class.forName("ClassName");
    Here class name is the name of the class whose instance u want to create dynamically.If u dont know the
    name exactly u need to use reflection.
    Object activeObject=className.newInstance();
    try this.
    -seenu_ch

  • Dynamic class instantiation

    Win2000
    SunOne Studio J2SE
    I am developing an application. I would like to instantiate classes and invoke methods dynamically, given a string containing the name of the class and/or a string containing the name of the method.
    I have the following code, and it compiles without error. However, when I run it, it throws a "ClassNotFoundException". I have read several articles that explain it as I have coded below.
    Any insights are appreciated. Thanks.
    try
    String className = "TestClass" ;
    String methodName = "OutMsg" ;
    Class testClass ;
    Object testObj ;
    Method testMethod ;
    testClass = Class.forName(className) ;
    testObj = testClass.newInstance() ;
    testMethod = testClass.getMethod(methodName, null) ;
    testMethod.invoke(testObj, null) ;
    catch (InstantiationException exc)
    System.out.println(exc) ;
    catch (ClassNotFoundException exc)
    System.out.println(exc) ;
    catch (IllegalAccessException exc)
    System.out.println(exc) ;
    catch (NoSuchMethodException exc)
    System.out.println(exc) ;
    catch (InvocationTargetException exc)
    System.out.println(exc) ;
    public class TestClass
    public void OutMsg()
    System.out.println("This is a test") ;

    You need to put complete class.
    I tried
    Class.forName("String");
    it complains that String is not found.
    But if I try
    Class.forName("java.lang.String");
    it works.
    MSN

  • Help with loading dynamic classes ..need help please

    i'm trying to design a program where by i can load dynamic classes
    the problem i'm getting is that only one class is loading.
    classes are loaded by their names,and index numbers of public methods from a linklist
    .When the program runs only the first class is ever loaded and only the methods of that class ..
    help please
    //class loader
    import java.lang.reflect.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.table.*;
    public class Test2 extends Thread
         public Class c;
         public Class Ray;
         public Class[] x;
         public static Object object = null;
         public Method[] theMethods;
         public static Method[] method,usemethod;
         public int methodcount;
         public static int MethodCt;     
         public static JList list;
    public Method[] startClass(String SetMethodName)
         try
              c = Class.forName(SetMethodName);
              object = c.newInstance();
              theMethods = c.getDeclaredMethods();
              // number of methods
              //methodcount = theMethods.length;
         catch (Exception e)
              e.printStackTrace();
    // return the array then invoke the particular method later
    return theMethods ;
    public void RunMethod(Method[] SomeMethod, int methodcount)
         try
              SomeMethod[methodcount].invoke( object,null );
         catch (Exception e)
              e.printStackTrace();
    // end class loader
    //main calling program
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing .*;
    import java.lang.reflect.*;
    public class JFMenu extends JFrame
         public static JMenu pluginMenu;
         public static JMenuBar bar;
         public static final Test2 w = new Test2();
    public static Method[] setmethod;
    private static ClassLinkList startRef = null;
    private static ClassLinkList linkRef3 = null;
    private static ClassLinkList startRef2 = null;
    private String ClassName,ShortCut;
    private int MethodNumber;
    private JMenuItem PluginItem;
         JFMenu()
              super (" JFluro ");     
              JMenu fileMenu = new JMenu("File");
              fileMenu.setMnemonic('F');
              JMenuItem exitItem = new JMenuItem("Exit");
              exitItem.setMnemonic('X');
              fileMenu.add(exitItem);
              exitItem.addActionListener
                   new ActionListener()
                        public void actionPerformed(ActionEvent event )
                             System.exit(0);
              JMenu pluginMenu = new JMenu("Plugins");
              pluginMenu.setMnemonic('P');
              startRef = new ClassLinkList ("Hello","Hello ",2,1926,"Painter");
              addToList("Foo","Foo ",0,1930,"Author");
              while (startRef.linkRef5 != null)
                   //pluginMenu.addSeparator();
                   ClassName = startRef.linkRef5.className;
                   ShortCut = startRef.linkRef5.shortcutName;
    MethodNumber = startRef.linkRef5.methodNumber;
    AddMenuItem(pluginMenu,ShortCut,ClassName,MethodNumber);
                   startRef.linkRef5 = startRef.linkRef5.next;
              // create menu bar and add JFMenu window to it
              JMenuBar bar = new JMenuBar();
              setJMenuBar(bar);
              bar.add(fileMenu);
              bar.add(pluginMenu);
              //attributes for JFMenu frame
              setSize(500,200);
              setVisible(true);
         }// end JFMenu constructor
         public void AddMenuItem(JMenu MainMenu, String shortcut,String className, final int methodCount )
              if (MainMenu==null)
                   return;
              //JMenuItem item;
              JMenuItem item = new JMenuItem(shortcut);
              MainMenu.add(item);
              setmethod = w.startClass(className);
              item.addActionListener
                   new ActionListener()
                        public void actionPerformed(ActionEvent event )
                             w.RunMethod(setmethod,methodCount);
              //item.addActionListener(ij);
         public JMenuItem AddMenuItem2(JMenu MainMenu, String shortcut)
              //if (MainMenu==null)
              //     return Main;
              //JMenuItem item;
              JMenuItem item = new JMenuItem(shortcut);
              MainMenu.add(item);
              //setmethod = w.startClass(className);
              //item.addActionListener(this);
                   new ActionListener()
                        public void actionPerformed(ActionEvent event )
                             w.RunMethod(setmethod,methodCount);
              //item.addActionListener(ij);
         return item;
         public void ReloadMenu(JMenuBar Bar, JMenu PluginMenu)
              if (Bar==null)
                   return;
              //     setJMenuBar(Bar);
              Bar.add(PluginMenu);
              //item.addActionListener(ij);
    public static void main (String args[])
              JFMenu menapp = new JFMenu();
    public static void addToList(String clname, String shcutname, int metnumber, int year2,
                                  String description) {
         // Create instance of class ClassLinkList
    ClassLinkList newRef = new ClassLinkList(clname,shcutname,metnumber,year2,
                                       description);
    // Add to linked list;
         startRef = startRef.addRecordToLinkedList(newRef);
    // end main calling program
    class Hello extends Thread
    public int getNum()
    System.out.println("I can be ");
    return 5;
    public void rayshowName()
    System.out.println("anything i want ");
    public void rayshowName3()
    System.out.println("to be ");
    class Foo extends Thread
    public int getNum()
    System.out.println("IMHOFF");
    return 5;
    public void rayshowName()
    System.out.println("raYMOND");
    // FAMOUS PERSONS LINKED LIST EXAMPLE
    // Frans Coenen
    // Saturday 15 January 2000
    // Depaertment of Computer Science, University of Liverpool
    class ClassLinkList {
    /* FIELDS */
    public String className;
    public String shortcutName;
    public int methodNumber;
    public int yearOfDeath;
    public String occupation;
    public ClassLinkList next = null;
    public ClassLinkList linkRef5 = this;
    public ClassLinkList startRef = null;
    /* CONSTRUCTORS */
    /* FamousPerson constructor */
    public ClassLinkList(String classname, String shortcutname, int methodnumber, int year2,
                                  String description) {
         className = classname;
         shortcutName = shortcutname;
         methodNumber = methodnumber;
         yearOfDeath = year2;
         occupation = description;
         next = null;
    /* METHODS */
    /* Output famous person linked list */
    public void outputClassLinkedList()
         //public ClassLinkList outputClassLinkedList() {
         ClassLinkList linkRef = this;
         // Loop through linked list till end outputting each record in turn
    while (linkRef != null)
         //System.out.println(linkRef5);
         System.out.println(linkRef.className + ", " + linkRef.shortcutName +
                   " (" + linkRef.methodNumber + "-" + linkRef.methodNumber +
                   "): " + linkRef.occupation);
         linkRef = linkRef.next;     
    //return linkRef;
    //public String ShowCasname()
    //return String ;     
    /* Add a new record to the linked list */
    public ClassLinkList addRecordToLinkedList(ClassLinkList newRef) {
         ClassLinkList tempRef, linkRef;
         // Test if new person is to be added to start of list if so return
    if (newRef.testRecord(this) ) {
         newRef.next = this;
         return(newRef);
         // Loop through remainder of linked list
         tempRef = this;
         linkRef = this.next;
         while (linkRef != null) {
         if (newRef.testRecord(linkRef)) {
         tempRef.next = newRef;
              newRef.next = linkRef;
              return(this);
         tempRef = linkRef;
         linkRef = linkRef.next;
    // Add to end
    tempRef.next = newRef;
         return(this);
    /* Delete a record from the linked list given the first and last name. Four
    posibilities:
    1) Record to be deleted is at front of list
    2) Record to be deleted is at end of list
    3) Record to be deleted is in middle of list
    4) Record not found. */
    public ClassLinkList deleteRecord(String lName, String fName) {
    ClassLinkList tempRef, linkRef;
    // Record at start of list
    if ((this.className == lName) & (this.shortcutName == fName))
         return(this.next);
         // Loop through linked list to discover if record is in middle of list.
         tempRef = this;
    linkRef = this.next;
    while (linkRef != null) {
         if ((linkRef.className == lName) & (linkRef.shortcutName == fName)) {
    tempRef.next = linkRef.next;
    return(this);
    tempRef = linkRef;
    linkRef = linkRef.next;
    // Record at end of list, or not found
    if ((linkRef.className == lName) & (linkRef.shortcutName == fName))
                        linkRef = null;
         else System.out.println("Record: " + lName + " " + fName + " not found!");
         return(this);
    /* TEST METHODS */
    /* Test whether new record comes before existing record or not. If so return
    true, false otherwise. */
    private boolean testRecord(ClassLinkList existingRef) {
         int testResult = className.compareTo(existingRef.className);
         if (testResult < 0) return(true);
         else {
         if ((testResult == 0) & (shortcutName.compareTo(existingRef.shortcutName) < 0 ))
                             return(true);
         // Return false
         return(false);
         public void addToList(String clname, String shcutname, int metnumber, int year2,
                                  String description)
         // Create instance of class Famous Person
    ClassLinkList newRef = new ClassLinkList(clname,shcutname,metnumber,year2,
                                       description);
    // Add to linked list;
         startRef = startRef.addRecordToLinkedList(newRef);

    I have a similar problem. I am writing a program to read the class names from database and instantiate several classes which extends from ServiceThread (an abstract class extending from Thread).
    rs = pStmt.executeQuery();
    while(rs.next()) {
    String threadclassname = rs.getString("classname").trim();
    try{
    ServiceThread threadinstance = (ServiceThread)Class.forName(threadclassname).newInstance();
    }catch ...
    So far, only the first class is ever instantiated and runs fine. But subsequent classes do not even get pass the "... ... Class.forName(...).newInstance();" line.
    Funny thing is that there are also no exceptions. The JVM just seem to hang there.

  • Dynamic class loading problem using unknown JAR archive and directory names

    I read the following article, which enlightened me a lot:
    Ted Neward: Understanding Class.forName().
    However, it took me some while to understand that my problem is the other way around:
    I know the name of the class, I know the name of the method,
    but my program/JVM does not know where to load the classes from.
    Shortly, my problem is that the server engine that I am writing
    uses two different versions of the same library.
    So I am trying out the following solution:
    My program is named TestClassPathMain.java
    Assume the two libraries are named JAR1.jar and JAR2.jar
    and the class/instance method that should
    be exposed to TestClassPathMain.java by them is named
    TestClass1.testMethod().
    As long as I was depending on just one library,
    I put JAR1.jar in the classpath before starting java,
    and I was happy for a while.
    At the moment I got the need to use another version of
    TestClass1.testMethod() packaged in JAR2.jar,
    a call would always access JAR1.jar's
    TestClass1.testMethod().
    I then decided to remove JAR1.jar from the classpath,
    and programmatically define two separate ClassLoaders, one for use
    with JAR1.jar and the other for use with JAR2.jar.
    However, the problem is only partly solved.
    Please refer to the enclosed code for details.
    (The code in the JAR1.jar/JAR2.jar is extremely simple,
    it just tells (by hardcoding) the name of the jar it is packaged in
    and instantiates another class packaged in the same jar using
    the "new" operator and calls a method on it. I don't enclose it.)
    The TestClassPathMain.java/UC1.java/UC2.java code suite was
    successfully compiled with an arbitrary of JAR1 or JAR2 in the classpath,
    however removed from the classpath at runtime.
    (I know that this could have been done (more elegantly...?) by producing an Interface,
    but I think the main problem principle is still untouched by this potential lack of elegancy(?))
    1) This problem should not be unknown to you experts out there,
    how is it generally and/or most elegantly solved?
    The "*** UC2: Variant 2" is the solution I would like best, had it only worked.
    2) And why arent "*** UC2: Variant 2" and
    "*** static UC2: Variant 2" working,
    while "*** Main: Variant 2" is?
    3) And a mal-apropos:
    Why can't I catch the NoClassDefFoundError?
    The output:
    *** Main: Variant 1 JAR 1 ***:
    Entering TestClass1.testMethod() packaged in JAR1.jar
    About to instantiate TestClass2 with the new operator
    About to call TestClass2.testMethod()
    Entering TestClass2.testMethod() packaged in JAR1.jar
    *** Main: Variant 1 JAR 2 ***:
    Entering TestClass1.testMethod() packaged in JAR2.jar
    About to instantiate TestClass2 with the new operator
    About to call TestClass2.testMethod()
    Entering TestClass2.testMethod() packaged in JAR2.jar
    *** Main: Variant 2 JAR 1 ***:
    Entering TestClass1.testMethod() packaged in JAR1.jar
    About to instantiate TestClass2 with the new operator
    About to call TestClass2.testMethod()
    Entering TestClass2.testMethod() packaged in JAR1.jar
    *** Main: Variant 2 JAR 2 ***:
    Entering TestClass1.testMethod() packaged in JAR2.jar
    About to instantiate TestClass2 with the new operator
    About to call TestClass2.testMethod()
    Entering TestClass2.testMethod() packaged in JAR2.jar
    *** UC1: Variant 1 JAR 1 ***:
    Entering TestClass1.testMethod() packaged in JAR1.jar
    About to instantiate TestClass2 with the new operator
    About to call TestClass2.testMethod()
    Entering TestClass2.testMethod() packaged in JAR1.jar
    *** UC1: Variant 1 JAR 2 ***:
    Entering TestClass1.testMethod() packaged in JAR2.jar
    About to instantiate TestClass2 with the new operator
    About to call TestClass2.testMethod()
    Entering TestClass2.testMethod() packaged in JAR2.jar
    *** static UC2: Variant 2 JAR 1 ***:
    Exception in thread "main" java.lang.NoClassDefFoundError: TestClass1
            at UC2.runFromJarVariant2_static(UC2.java:56)
            at TestClassPathMain.main(TestClassPathMain.java:52)
    TestClassPathMain.java
    import java.lang.reflect.InvocationTargetException;
    import java.lang.reflect.Method;
    import java.net.MalformedURLException;
    import java.net.URL;
    import java.net.URLClassLoader;
    public class TestClassPathMain {
        public static void main(final String args[]) throws MalformedURLException, ClassNotFoundException, InstantiationException, SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException {
                // Commented out because I cannot catch the NoClassDefFoundError.
                // Why?
                try {
                    final TestClass1 testClass1 = new TestClass1();
                    System.out.println(
                        "\nThe class TestClass1 is of some unexplicable reason available." +
                        "\nFor the purpose of the test, it shouldn't have been!" +
                        "\nExiting");
                    System.exit(1);
                } catch (NoClassDefFoundError e) {
                    System.out.println("\nPositively confirmed that the class TestClass1 is not available:\n" + e);
                    System.out.println("\n\nREADY FOR THE TEST: ...");
                // Works fine
                System.out.println("\n*** Main: Variant 1 JAR 1 ***:");
                runFromJarVariant1("file:/W:/java/eclipse/workspaces/simped_test/CP1/JAR1.jar");
                System.out.println("\n*** Main: Variant 1 JAR 2 ***:");
                runFromJarVariant1("file:/W:/java/eclipse/workspaces/simped_test/CP2/JAR2.jar");
                // Works fine
                System.out.println("\n*** Main: Variant 2 JAR 1 ***:");
                runFromJarVariant1("file:/W:/java/eclipse/workspaces/simped_test/CP1/JAR1.jar");
                System.out.println("\n*** Main: Variant 2 JAR 2 ***:");
                runFromJarVariant1("file:/W:/java/eclipse/workspaces/simped_test/CP2/JAR2.jar");
                // Works fine
                final UC1 uc1 = new UC1();
                System.out.println("\n*** UC1: Variant 1 JAR 1 ***:");
                uc1.runFromJarVariant1("file:/W:/java/eclipse/workspaces/simped_test/CP1/JAR1.jar");
                System.out.println("\n*** UC1: Variant 1 JAR 2 ***:");
                uc1.runFromJarVariant1("file:/W:/java/eclipse/workspaces/simped_test/CP2/JAR2.jar");
                // Crashes
                System.out.println("\n*** static UC2: Variant 2 JAR 1 ***:");
                UC2.runFromJarVariant2_static("file:/W:/java/eclipse/workspaces/simped_test/CP1/JAR1.jar");
                System.out.println("\n*** static UC2: Variant 2 JAR 2 ***:");
                UC2.runFromJarVariant2_static("file:/W:/java/eclipse/workspaces/simped_test/CP2/JAR2.jar");
                // Crashes
                final UC2 uc2 = new UC2();
                System.out.println("\n*** UC2: Variant 2 JAR 1 ***:");
                uc2.runFromJarVariant2("file:/W:/java/eclipse/workspaces/simped_test/CP1/JAR1.jar");
                System.out.println("\n*** UC2: Variant 2 JAR 2 ***:");
                uc2.runFromJarVariant2("file:/W:/java/eclipse/workspaces/simped_test/CP2/JAR2.jar");
        private static void runFromJarVariant1(final String jarFileURL)
            throws MalformedURLException,
                   ClassNotFoundException,
                   InstantiationException,
                   IllegalArgumentException,
                   IllegalAccessException,
                   InvocationTargetException,
                   SecurityException,
                   NoSuchMethodException {
            final URL url = new URL(jarFileURL);
            final URLClassLoader cl =
                new URLClassLoader(new URL[]{url},
                                   Thread.currentThread().getContextClassLoader());
            final Class clazz = cl.loadClass("TestClass1");
            final Object testClass1 = clazz.newInstance();
            final Method testMethod1 = clazz.getMethod("testMethod", null);
            testMethod1.invoke(testClass1, null);
        private static void runFromJarVariant2(final String jarFileURL)
            throws MalformedURLException,
                   ClassNotFoundException,
                   InstantiationException,
                   IllegalArgumentException,
                   IllegalAccessException,
                   InvocationTargetException,
                   SecurityException,
                   NoSuchMethodException {
            final URL url = new URL(jarFileURL);
            final URLClassLoader cl =
                new URLClassLoader(new URL[]{url},
                                   Thread.currentThread().getContextClassLoader());
            final Class clazz = cl.loadClass("TestClass1");
            final TestClass1 testClass1 = new TestClass1();
            testClass1.testMethod();
    UC1.java
    import java.lang.reflect.InvocationTargetException;
    import java.lang.reflect.Method;
    import java.net.MalformedURLException;
    import java.net.URL;
    import java.net.URLClassLoader;
    public class UC1 {
        public void runFromJarVariant1(final String jarFileURL)
            throws MalformedURLException,
                   ClassNotFoundException,
                   InstantiationException,
                   IllegalArgumentException,
                   IllegalAccessException,
                   InvocationTargetException,
                   SecurityException,
                   NoSuchMethodException {
            final URL url = new URL(jarFileURL);
            final URLClassLoader cl =
                new URLClassLoader(new URL[]{url},
                                   Thread.currentThread().getContextClassLoader());
            final Class clazz = cl.loadClass("TestClass1");
            final Object testClass1 = clazz.newInstance();
            final Method testMethod1 = clazz.getMethod("testMethod", null);
            testMethod1.invoke(testClass1, null);
    UC2.java
    import java.lang.reflect.InvocationTargetException;
    import java.net.MalformedURLException;
    import java.net.URL;
    import java.net.URLClassLoader;
    public class UC2 {
        public void runFromJarVariant2(final String jarFileURL)
        throws MalformedURLException,
               ClassNotFoundException,
               InstantiationException,
               IllegalArgumentException,
               IllegalAccessException,
               InvocationTargetException,
               SecurityException,
               NoSuchMethodException {
            final URL url = new URL(jarFileURL);
            final URLClassLoader cl =
                new URLClassLoader(new URL[]{url},
                                   Thread.currentThread().getContextClassLoader());
            final Class clazz = cl.loadClass("TestClass1");
            final TestClass1 testClass1 = new TestClass1();
            testClass1.testMethod();
         * Identic to the "runFromJarVariant2" method,
         * except that it is static
        public static void runFromJarVariant2_static(final String jarFileURL)
        throws MalformedURLException,
               ClassNotFoundException,
               InstantiationException,
               IllegalArgumentException,
               IllegalAccessException,
               InvocationTargetException,
               SecurityException,
               NoSuchMethodException {
            final URL url = new URL(jarFileURL);
            final URLClassLoader cl =
                new URLClassLoader(new URL[]{url},
                                   Thread.currentThread().getContextClassLoader());
            final Class clazz = cl.loadClass("TestClass1");
            final TestClass1 testClass1 = new TestClass1();
            testClass1.testMethod();
    }

    2. i need to load the class to the same JVM (i.e. to
    the same environment) of the current running
    aplication, so that when the loaded class is run, it
    would be able to invoke methods on it!!!
    ClassLoader(s) do this. Try the URLClassLoader.
    (I was talking about relatively esoteric "security"
    issues when I mentioned the stuff about Class objects
    "scope".) You might use the URLClassLoader kind of
    like this.
    Pseudo-code follows:
    // setup the class loader
    URL[] urls = new URL[1];
    urls[0] = new URL("/path/to/dynamic/classes");
    URLClassLoader ucl = new URLClassLoader(urls);
    // load a class & use make an object with the default constructor
    Object tmp = ucl.loadClass("dynamic.class.name").newInstance();
    // Cast the object to a know interface so that you can use it.
    // This may be used to further determine which interface to cast
    // the class to. Or it may simply be the interface to which all
    // dynamic classes have to conform in your program.
    InterfaceImplementedByDynamicClass loadedObj =
        (InterfaceImplementedByDynamicClass)tmp;It's really not as hard as it sounds, just write a little test of
    this and you will see how it works.

  • Dynamic class loading from directory on server

    Hello,
    I am not sure if this is right forum, but I think it is more weblogic then ADF issue...
    I am trying to create and load dynamically classes in weblogic (10.3.2.0). It is ADF application which I deploy to the weblogic server.
    When I print ((GenericClassLoader)this.getClass().getClassLoader()).getFinderClassPath()I see the path to my directory (of course not just this path) C:\...\system11.1.1.2.36.55.36\DefaultDomain\servers\DefaultServer\tmp\_WL_user\test\753the\dynamicClasses(I have added directory dynamicClasses to manifest for deployment WAR profile).
    In this directory I create class files. I have checked it, files are really created there.
    When I try to load created class with the same classloader, for which I have printed classpath, ClassNotFoundException is thrown.
    Please where could be the problem? Isn't it possible to load classes from directory instead of jar, do I need some special server configuration,...?
    Thank you in advance
    Qjeta

    Hi Qjeta,
    I am not sure but you can give it a try using URLClassLoader...Which we generally use for DynamicClassLoading:
    import java.net.URLClassLoader;
    <font color=maroon>
    String path="C:/.../system11.1.1.2.36.55.36/DefaultDomain/servers/DefaultServer/tmp/_WL_user/test/753the/dynamicClasses";
    *URLClassLoader loader = new URLClassLoader(new URL[] { new URL(path) });*
    Class c = loader.loadClass ("your.class.NameHere");
    </font>
    // Load class from class loader. filly qualified class name (means classname with package name) is the name of the class to be loaded
    in the above code the "C:/.../system11.1.1.2.36.55.36/DefaultDomain/servers/DefaultServer/tmp/_WL_user/test/753the/dynamicClasses" should be the location of the directory where your classes are placed....If you want to load a perticular Jar then you need to write the jarfile name as well like following:
    C:/.../system11.1.1.2.36.55.36/DefaultDomain/servers/DefaultServer/tmp/_WL_user/test/753the/dynamicClasses/Myapplication.jar
    .================================
    If the above code works for you then later you can even try to enhance your code by doing the following:
    Thread.currentThread().setContextClassLoader(urlClassLoaderRef);
    Thanks
    Jay SenSharma
    http://jaysensharma.wordpress.com (WebLogic Wonders Are Here)

  • Dynamic Class Loading and Unloading

    I am trying to create a system where the class name and method name is
    picked up from a meta-data database and executed.
    This was accompanied using Dynamic Class loading. I tried to extend this to
    support versioning of meta-data. Here depending on the version of meta-data
    different libraries can be loaded and different implementations of object
    with the same name can be executed. This does not seem to work with Forte
    3.0.
    When the second Library is loaded the method execution does not work.
    (Even though the unload flag on the LoadLibrary is set)
    If the application is stopped and restarted pointing to the second library
    there is no problem. In a running application a dynamically loaded library
    does not seem to unload and reload a new library for the same class names.
    Has anyone tried sometime similar, is there a workaround for this type of
    problem.
    - Vivek

    I am trying to create a system where the class name and method name is
    picked up from a meta-data database and executed.
    This was accompanied using Dynamic Class loading. I tried to extend this to
    support versioning of meta-data. Here depending on the version of meta-data
    different libraries can be loaded and different implementations of object
    with the same name can be executed. This does not seem to work with Forte
    3.0.
    When the second Library is loaded the method execution does not work.
    (Even though the unload flag on the LoadLibrary is set)
    If the application is stopped and restarted pointing to the second library
    there is no problem. In a running application a dynamically loaded library
    does not seem to unload and reload a new library for the same class names.
    Has anyone tried sometime similar, is there a workaround for this type of
    problem.
    - Vivek

  • Dynamic class reloading in modular web application

    Hi.
    My web application has these requirements:
    A. Functional modularization (like plug-ins). Modules will be simple jars containing application logic classes: dto beans, business logic services, dao (jpa), framework stuff (Struts2), etc...
    B. At runtime and without restarting the application "class loading" must be aware of classes inside new, changed and removed modules.
    C. Some of these jars will be outside the web application folder (WEB-INF/lib), possibly outside the container itself too.
    My question:
    1. Can I achieve all or some of my requirements with a Java web application?
    2. How should I manage the modules?
    3. Do I need some special web container feature (maybe osgi)?
    4. Can I use a custom class loader in my application?
    The architecture objectives are:
    I. Provide scalability.
    II. Efficient development process (independent deployment and no application restart required).
    III. Better production support (no application restart required for changes).
    More on the architecture:
    a). Functional scalability, meaning this that my application may functionally grow up to an indeterminate number of small functional modules.
    b). Modules will be developed, deployed and maintained independently so the application discovers and loads classes on demand.
    c). Avoid a big .war file containing all the small modules because a small change in one module would involves deploying all the other modules (possibly hundreds o even thousands of them) and restarting the application.
    d). Above point involves dynamic class reloading.
    I guess this is addressed by OSGI (looks like heavy to deal with), Jigsaw (still under development) and maybe others. I think the key point is the class loader. I will develop a custom class loader but maybe you have some advice for me before starting to develop.
    Thanks and regards.

    Classes maintained by the container should not be loaded by an application. You want the container to read those classes and react accordingly. Most of those classes are read when the container starts up a container restart will be required. Trying to leverage another container within a container does not sound like it will be worth (if you can get it to work).
    Perhaps you should state the problem that you are trying to solve with these modules so that others may suggest more feasible solutions to achieve your target goals.

  • Dynamic class loading failed, why?

    Hi there!
    We are using WebLogic 5.1 togehter with Apache1.3.22/Tomcat4.01. It all worked
    fine for about 2 month. All of a sudden, dynamic class loading refuses to work.
    From one day to the other I got the excpetion: javax.naming.CommunicationException.
    Root exception is weblogic.rmi.UnmarshalException: Unmarshalling return
    - with nested exception:
    [java.lang.ClassNotFoundException: class com.dsh.egb.aks.betrieb.ejbs.AnmeldenEJBHomeImpl_ServiceStub
    previously not found]
    Why does this happen? I can not remember having touched any properties.
    Please help,
    Heiner

    If you were relying on client network classloading stubs from WebLogic, you
    can test if it still works by pointing your browser to
    htpp://yourweblogic:7001/classes/com/dsh/egb/aks/betrieb/ejbs/AnmeldenEJBHomeImpl_ServiceStub.class
    Heiner Amthauer <[email protected]> wrote:
    Hi there!
    We are using WebLogic 5.1 togehter with Apache1.3.22/Tomcat4.01. It all worked
    fine for about 2 month. All of a sudden, dynamic class loading refuses to work.
    From one day to the other I got the excpetion: javax.naming.CommunicationException.
    Root exception is weblogic.rmi.UnmarshalException: Unmarshalling return
    - with nested exception:
    [java.lang.ClassNotFoundException: class com.dsh.egb.aks.betrieb.ejbs.AnmeldenEJBHomeImpl_ServiceStub
    previously not found]
    Why does this happen? I can not remember having touched any properties.
    Please help,
    Heiner--
    Dimitri

  • Dynamic class loading in J2ME

    Hi all,
    Couple of questions. Is dynamic class loading using classloaders supported in any, if not all versions of J2ME? I guess I should ask first, what exactly does J2ME cover? I see KVM, but do watches and PDA's, set top boxes, refrigerators and so forth all run the same J2ME JVM? Or are their "less feature full" versions? I was hoping the J2ME spec would be the "lowest common denominator" to program for, but I thought I read somewhere that small devices like watches may even have a "smaller" J2ME JVM or something, less capable. So can I write code for J2ME and it will run on all small devices like cell phones, pda's, and so forth? Or is there another J2ME version, perhaps small than J2ME.
    So, from what I have found so far, it appears dynamic class loading is done at startup from a DB (of sorts) as opposed to being able to dynamically find/load classes. If this is so, is there any way to support downloading and reloading new classes like you can with J2SE, such as the hot-swap feature of web servers? Does Class.forName() at least work in that you can "replace" a class with a new version, even if it is not able to have a separate classloader instance? My guess is that J2ME supports only a single classloader space, but I thought I read somewhere that Class.forName() is available. J2ME API shows it I believe, but I could be wrong.
    Any help on this topic would be appreciated.
    Thanks.

    Dynamic class loading is not available in most (if not all) J2ME profiles and configurations. Class.forName() is available (at least in the MID profile), but not to be used for dynamic class loading. It can be used when using device-specific APIs where you can try to load a class containing device specific methods (for example a class that works only on certain Nokia phones, and has methods playSound() and vibrate(), which are not available in MIDP), and if you catch a ClassNotFound exception you can load a class that doesn't use the device specific APIs and contains stubs of the methods, or you can disable certain features in you application that need those features. For an example implementation you can have a look at Nokia's Block Game example (available from their developer site - http://www.forum.nokia.com/main.html).
    As for your other more general questions about different JVM's and such, you should read all about the different configurations and profiles available in J2ME (plenty of information using in the J2ME link on this site).

Maybe you are looking for