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

Similar Messages

  • Diffrence between Class.forName() and new Operator

    What is diffrence between class.forName() and new operator.Please tell in much detail.
    Also about classloader.loadclass.
    Suppose the class that we are tring to load with the help of class.forname is not compiled. Again if I make changes at runtime to that class will that get reflected.

    What is diffrence between class.forName() and new
    operator.Please tell in much detail.Class.forName loads a class. The new operator creates a new instance. Apple trees and apples.
    Also about classloader.loadclass.Read the API.
    Suppose the class that we are tring to load with the
    help of class.forname is not compiled.Then you can't load it and get an exception. Read the API.
    Again if I
    make changes at runtime to that class will that get
    reflected.Depends on the changes and when exactly you do them.

  • Dynamic queue name with JMS Queue XML?

    Hi,
    Is it possible to use dynamic queue name with JMS Queue XML?
    I tried using a variable in the JNDI URL, and supply the value in a package. I specified the following in the JNDI URL in the Topology:
    e.g.
    <JMS_RESOURCE>?d=<DTD_FILE>&s=<SCHEMA>&JMS_DESTINATION=#PROJECT_NAME.dest_var
    I declared and set the variable in a package, then tried to load data from the above data server to database. But executing this package gave me the following error:
    7000 : null : java.sql.SQLException: javax.jms.JMSException: Cannot find the target in JNDI (#PROJECT_NAME.dest_var)
    java.sql.SQLException: javax.jms.JMSException: Cannot find the target in JNDI (#PROJECT_NAME.dest_var)
         at com.sunopsis.jdbc.driver.bg.executeQuery(bg.java)
         at com.sunopsis.jdbc.driver.bh.executeQuery(bh.java)
         at com.sunopsis.jdbc.driver.l.f(l.java)
         at com.sunopsis.jdbc.driver.l.executeUpdate(l.java)
         at com.sunopsis.sql.SnpsQuery.executeUpdate(SnpsQuery.java)
         at com.sunopsis.dwg.dbobj.SnpSessTaskSql.execSrcOrders(SnpSessTaskSql.java)
         at com.sunopsis.dwg.dbobj.SnpSessTaskSql.treatTaskTrt(SnpSessTaskSql.java)
         at com.sunopsis.dwg.dbobj.SnpSessTaskSqlC.treatTaskTrt(SnpSessTaskSqlC.java)
         at com.sunopsis.dwg.dbobj.SnpSessTaskSql.treatTask(SnpSessTaskSql.java)
         at com.sunopsis.dwg.dbobj.SnpSessStep.treatSessStep(SnpSessStep.java)
         at com.sunopsis.dwg.dbobj.SnpSession.treatSession(SnpSession.java)
         at com.sunopsis.dwg.cmd.DwgCommandScenario.treatCommand(DwgCommandScenario.java)
         at com.sunopsis.dwg.cmd.DwgCommandBase.execute(DwgCommandBase.java)
         at com.sunopsis.dwg.cmd.e.i(e.java)
         at com.sunopsis.dwg.cmd.g.y(g.java)
         at com.sunopsis.dwg.cmd.e.run(e.java)
         at java.lang.Thread.run(Unknown Source)
    Am I doing it wrongly?
    Thanks!

    hi,
    as it's not in Adapter-Specific Message Properties
    http://help.sap.com/saphelp_nw04/helpdata/en/10/b1b4c8575a6e47954ad63438d303e4/content.htm
    looks like you cannot do it with jms adapter in standard
    use proxy or your own adapter instead
    Regards,
    michal
    <a href="/people/michal.krawczyk2/blog/2005/06/28/xipi-faq-frequently-asked-questions"><b>XI / PI FAQ - Frequently Asked Questions</b></a>

  • Hey,i forgot my login password,so i changed the password by using terminal command(reset password).now i have new user name with new password,but i can't find  my data which i have saved on mac.please help me out in this matter.

    hey,i forgot my login password,so i changed the password by using terminal command(reset password).now i have new user name with new password,
    but i can't find  my data which i have saved on mac.the storage is showing data used and free space on the disk
    please help me out in this matter.

    How did you change your user name?
    resetpassword wouldn't have done it. If you managed to create a new user, then your data is still in the old account.

  • Is there any Similar between Class.forName() and new operator ???

    Plz tel me is there any Similar between Class.forName() and new operator ??? i have been asked this ques in interview

    You probably should have used the other thread:
    http://forum.java.sun.com/thread.jspa?threadID=792678
    To add a little confusion to the matter...Class objects are in fact objects. They're objects representing classes. So, in a sense, I guess, you could say they're similar -- in each you get an object. But in practice Class objects and all other objects should be considered semantically different unless you're doing some pretty unusual stuff. Also Class.forName is more of a factory method than a constructor.

  • Would use iphone?if apple replaces ios with new operating system??

    would use iphone?if apple replaces ios with new operating system??would you buy any iPhone ??also you could not buy any iPhone 7,with any ios?

    Apple have just updated their iOS to iOS 8 so what are you on about?
    Do you have a valid question here or not?

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

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

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

  • Class.forName() doesn't take dynamic class name

    String name="";
    String country="";
    String className = name + "_" + language + "_" + country;
    Class thisClass = Dynamicclassload.classLoad(className);
    System.out.println(className);
    Class class1 = Class.forName(className);
    child = (ResourceBundle) class1.newInstance();
    child.setParent( bundle );
    bundle = child;
    System.out.println("I am here");
    As i am passing classname as variable it throws an exception class not found exception.but if we write class name as the parameter of class.forName().it works.i am implementing in j2me
    why this happen? give me solution.

    The following classpackage test;
    public class TestLoad {
        String aString = "This is a Test";
        Integer anInteger = new Integer(42);
        public TestLoad() {
            System.out.println("aString = " + aString + ", anInteger = " + anInteger);
    }works correctly when loaded and instantiated by this class:package test;
    import java.util.logging.Logger;
    public class ExecuteTest {
        public static final Logger log = Logger.getAnonymousLogger();
        public static void main(String[] args) {
            try {
                Class clazz = Class.forName("test.TestLoad");
                TestLoad test = (TestLoad) clazz.newInstance();
            } catch (Exception ex) {
                log.severe(ex.toString());
    }and produces the string "aString = This is a Test, anInteger = 42"
    I used the following version of Java on Windows 2000
    java version "1.4.0"
    Java(TM) 2 Runtime Environment, Standard Edition (build 1.4.0-b92)
    Java HotSpot(TM) Client VM (build 1.4.0-b92, mixed mode)

  • JAXB compiler for class names with special characters

    Hi,
    I trying to run the xjc against an XSD where element names (class names) have an "_" in them. For eg ACCOUNT_AKG.
    JAXB creates a class ACCOUNTAKG and omits the "_". I need "_" to be preserved in the class name of the class is generated.
    Can someone show me the right direction , so I can create classes with "_" preserved in the class name.
    This would be a big help
    thanks
    Jax

    Hi,
    I trying to run the xjc against an XSD where element names (class names) have an "_" in them. For eg ACCOUNT_AKG.
    JAXB creates a class ACCOUNTAKG and omits the "_". I need "_" to be preserved in the class name of the class is generated.
    Can someone show me the right direction , so I can create classes with "_" preserved in the class name.
    This would be a big help
    thanks
    Jax

  • Help for dynamic class name

    In actionscript 2.0, the following codes dynamically attach a
    symbol
    in the library to the stage:
    var i:Number=Math.floor(Math.random*10);
    this.attachMovie("symbol"+i,this.getNextHighestDepth());
    where symbol0 ~ symbol9 are linkage id of 10 symbols in the
    library.
    While in ActionScript 3.0, I have a difficulty doing similar
    thing.
    If I want to attach a symbol to the stage, the code may look
    like
    var a_mc:MovieClip=new Symbol0();
    this.addChild(a_mc);
    but I don't know how I can attach randomly
    1 var i:int=Math.floor(Math.random()*10);
    2 var a_mc:MovieClip=new [Symbol+i]();
    3 this.addChild(a_mc);
    I found I need script like line 2, but it doesn't work
    obviously.
    Is the convenient way to do this?
    thanks very much for help!

    import flash.utils.*;
    var i:int=Math.floor(Math.random()*10);
    var classDef:Class = getDefinitionByName("Symbol"+i) as
    Class;
    this.addChild(new classDef() as DisplayObject);

  • Problems with New operating system

    I am using iphone 4s since i updated new operating system my phone unable to connect wifi autometically becomes very slow not supporting apps and its rebooting autometically.

    Try Settings > General > Reset > Reset All Settings.

Maybe you are looking for

  • Can't Find Hidden Programmes

    I had a Facebook app on my phone and by mistake hide it. Any ideas how I can get it back?

  • Help ORA-02049

    HELP HELP HELP!! Following error on Oracle 8.1.7 SQR 5528) ORACLE OCIStmtExecute error 2049 in cursor 38: ORA-02049: timeout: distributed transaction waiting for lock ORA-02063: preceding line from XAPPPRD Error on line 3155: (SQR 3735) Could not exe

  • Configure EP to display contents from Solution Manager

    Hello, How to Configure EP to display contents from Solution Manager? I want to access Solution Monitoring through Portal, how to do this? I will appreciate if someone can help me, Waiting for reply, Regards Sharmishtha

  • Insert and update command types in dml handlers

    Hi, I have been setting up streams in Oracle 9.2.0.4. I have been writing dml handlers for a table 'LARGE_INSERT_CLONE' in the 'SQUID' schema. My requirement is as follows. 1. If a record is inserted in the table 'LARGE_INSERT_CLONE' in the source da

  • AddressBook sync with Exchange

    I'm trying to sync my AddressBook with my company's exchange server. I setup in the AddressBook preferences, then I run iSync, show the status in the menubar and run sync now. I can see from my network traffic that a good deal of data is going back a