DefaultMutableTreeModel, and casting TreeModel - DefaultMutableTreeModel

I have a workflow object, from which I create a workflowTreeModel and display this in a JTree - all works OK....
I now need to create a DefaultMutableTreeModel from the same workflow object and I in need of some pointers. (please)
All the examples I can find create a number of DefaultMutableTreeNodes (eg, red, blue, green) and add them to a DefaultMutableTreeNode (eg.color)...
As I already have a workflow object that I am trying to display this approach doesn't fit. Is there anyway to create a DefaultMutableTreeModel in the same way as I am creating the TreeModel?
Looking at the 'understanding the treeModel' tutorial from Sun I see that I should be able to cast my workflowTreeModel to a DefaultTreeModel using:
JTree() myTree = new JTree(workflowTreeModel);
DefaultTreeModel t = (DefaultTreeModel) myTree.getModel();
However I get a class cast exception trying to do this - I imagine this is as a result of the way the workflowTreeModel is created (code below).
If anyone can show me the correct way to create a DefaultTreeModel from my workflow object I would be grateful....
(workflowTreeModel code: )
public class WorkflowTreeModel extends AbstractWorkflowTreeModel {
     * Commons Logger for this class
    private static final Log logger = LogFactory.getLog(WorkflowTreeModel.class);
    private Workflow rootWorkflow;     
     public WorkflowTreeModel(Workflow root) {
          rootWorkflow = root;
     /* (non-Javadoc)
      * @see javax.swing.tree.TreeModel#getRoot()
     public Object getRoot() {
          return rootWorkflow.getSequence();
     /* (non-Javadoc)
      * @see javax.swing.tree.TreeModel#getChildCount(java.lang.Object)
     public int getChildCount(Object parent) {
          int i = 0;
          if(parent instanceof Workflow) {
               i = 1;
          else if(parent instanceof Sequence) {
               Sequence s = (Sequence)parent;
               i = s.getActivityCount();
          else if(parent instanceof Flow) {
               Flow f = (Flow)parent;
               i = f.getActivityCount();
          else if(parent instanceof For) {
               For f = (For)parent;
               Sequence s = (Sequence)f.getActivity();
               i = s.getActivityCount();
          else if (parent instanceof If) {
               If a = (If)parent;
               if (a.getElse() != null && a.getElse() instanceof Else)
                    i = i + 1;
               if (a.getThen() != null && a.getThen() instanceof Then)
                    i = i + 1;
          else if (parent instanceof Else || parent instanceof Then) {
             i = 1;
          else if (parent instanceof For || parent instanceof Parfor || parent instanceof While) {
               i = 1;
          else if (parent instanceof Scope) {
               i = 1;
          else if (parent instanceof Script) {
               i = 1;
          return i;
     /* (non-Javadoc)
      * @see javax.swing.tree.TreeModel#isLeaf(java.lang.Object)
     public boolean isLeaf(Object node) {
          boolean b = true;
          if (node instanceof Sequence) {
               if (((Sequence)node).getActivityCount() > 0)
                    b = false;
          if (node instanceof Flow) {
               if (((Flow)node).getActivityCount() > 0)
                   b = false;
          else if (node instanceof If || node instanceof Else || node instanceof Then) {
               b = false;
          else if (node instanceof For || node instanceof Parfor || node instanceof While) {
               b = false;
          else if (node instanceof Scope) {
               b = false;
          else if (node instanceof Workflow) {
               b = false;
          else if (node instanceof Script) {
               b = false;
          return b;
     /* (non-Javadoc)
      * @see javax.swing.tree.TreeModel#addTreeModelListener(javax.swing.event.TreeModelListener)
     public void addTreeModelListener(TreeModelListener l) {
     /* (non-Javadoc)
      * @see javax.swing.tree.TreeModel#removeTreeModelListener(javax.swing.event.TreeModelListener)
     public void removeTreeModelListener(TreeModelListener l) {
     /* (non-Javadoc)
      * @see javax.swing.tree.TreeModel#getChild(java.lang.Object, int)
     public Object getChild(Object parent, int index) {
          Object ob = null;
          if (parent instanceof Workflow){
               Workflow w = (Workflow)parent;
               ob = w.getSequence();
          else if(parent instanceof Sequence) {
               Sequence s = (Sequence)parent;
               ob = s.getActivity(index);
          else if(parent instanceof Flow) {
               Flow f = (Flow)parent;
               ob = f.getActivity(index);
          else if (parent instanceof For) {
               For f = (For)parent;
               Sequence s = (Sequence)f.getActivity();
               ob = s.getActivity(index);
          else if (parent instanceof Parfor) {
               Parfor p = (Parfor)parent;
               ob = p.getActivity();
          else if (parent instanceof Scope) {
               Scope s = (Scope)parent;
               ob = s.getActivity();
          else if (parent instanceof While) {
               While w = (While)parent;
               ob = w.getActivity();
          else if (parent instanceof If) {
               If i = (If)parent;
               if (index == 0) {
                    if ((i.getThen() != null) && (i.getThen() instanceof Then)){
                         ob = i.getThen();
                    else if ((i.getElse() != null) && (i.getElse() instanceof Else)){
                         ob = i.getElse();
               if (index == 1) {
                    if ((i.getElse() != null) && (i.getElse() instanceof Else)){
                         ob = i.getElse();
                    else if ((i.getThen() != null) && (i.getThen() instanceof Then)){
                         ob = i.getThen();
          else if (parent instanceof Else) {
               Else e = (Else)parent;               
               ob = e.getActivity();               
          else if (parent instanceof Then) {
               Then t = (Then)parent;               
               ob = t.getActivity();               
          else if (parent instanceof Script) {
               Script s = (Script)parent;
               ob = s.getBody();
          return ob;
     /* (non-Javadoc)
      * @see javax.swing.tree.TreeModel#getIndexOfChild(java.lang.Object, java.lang.Object)
     public int getIndexOfChild(Object parent, Object child) {
          logger.debug("getIndexOfChild");
          // TODO Auto-generated method stub
          return -1;
     /* (non-Javadoc)
      * @see javax.swing.tree.TreeModel#valueForPathChanged(javax.swing.tree.TreePath, java.lang.Object)
     public void valueForPathChanged(TreePath path, Object newValue) {
          // TODO Auto-generated method stub
public abstract class AbstractWorkflowTreeModel extends WorkflowTreeModelSupport implements TreeModel {
}

JTree() myTree = new JTree(workflowTreeModel);
DefaultTreeModel t = (DefaultTreeModel) myTree.getModel();the only way you can cast this is that workflowTreeModel must extends DefaultTreeModel
What you can do is to for WorkFlowTreeMdeol to extends DefaultTreeModel
or case it to WorkFlowTreeModel
JTree() myTree = new JTree(workflowTreeModel);
WorkFlowTreeModel model = (WorkFlowTreeModel) myTree.getModel();

Similar Messages

  • Get values from a node and Cast it back to a table

    Hi guys!
    Anyway know if it is possible to get the values from a table(That was binded previously) and cast it back to a table structure so i can manupilate the fields inside...
    My scenario here is to get an input and mass update tis input into the corresponding field in the table...
    Any suggestions are welcome and points will be awarded generously! ")

    Hi Ravikiran,
    In your example you update node node_list with the content of internal table tab_list..
    The content of the node can be retrieved as an itab using:
      tab_list = node_list->get_static_attributes_table( ).
    This method only returns the values static attributes of the node. Dynamic attributes added at runtime using dynamic programming are not returned, since they are managed in a different inside of the context node.
    Best regards,
    Thomas

  • Get runtime class and cast object to it?

    Hi,
    public interface Msg
    Msg msg=msgLib.get(msgType);
    Msg msg2=msg.clone(); //problem! cannot find clone in  x.y.Msg!
    ...Shouldn't msg be resolved to the implementing class (MsgReply for example) and use the "clone()" method, that i have declared in that class -which overrides the one of Object class?
    If no, is there a way to find the runtime class -probably use "getClass"- and cast to it? How?
    Thanks

    There are many implementing classes; i want to get the runtime class. Something like:
    (msg.getClass())msg.clone();
    Message was edited by:
    uig

  • Method chaining and casting

    I was wondering if anyone knows whether it is possible to somehow apply method chaining on an object that requires a cast.
    For example:
    ArrayList ar = new ArrayList();
    ar.add(new Integer(3));
    int i = ar.get(0).intValue();The third line obviously produces a compile error to the effect that you can't call method intValue() on object Object.
    To get the int value from the ArrayList above I have to do the following:
    ArrayList ar = new ArrayList();
    ar.add(new Integer(3));
    Integer intObject = (Integer)ar.get(0);
    int i = intObject.intValue();Is it at all possible to get the int value somehow without explicitly creating an Integer object? Is there a possible way to combine method chaining and casting in this case?

    You may combine the two lines by casting at the same time:
    int i = ((Integer)ar.get(0)).intValue();
    Notice the additional brackets to help the compiler understand the precedence of your intentions. It makes no sense if the compile tries to call intValue THEN cast to Integer.
    When you call:
    Integer intObject = (Integer)ar.get(0);
    No Integer object is created, only a reference to the object is created. I'm not sure if an implicit reference is created in the previous example, but I see no substantial benefit using the first method. In fact I won't use it as its not very readable (to me).

  • Trouble with primitive arrays and casting, lesson 521

    hi everyone!
    there is a problem i discovered right now - after years with java where was no necessity to do this.....
    and i'm shure this must have been the topic already, but i couldn't find any helpful resource :-/
    right here we go:
    1. an array is a (special) kind of object.
    2. there are "primitive" arrays and such containing references to objects. of course - and i imagine why - they are treated differently by the VM.
    3. then both are - somehow - subclasses of Object. whereas primitive types are not really, primitive-arrays are. this is hidden to the programmer....
    4. any array can be "pointed" at via local Object variable, like this:
    Object xyz = new int[6];
    5. arrays of Objects (with different dimensions) can be casted, like this:
      Object pointer = null;
      Object[]   o  = new SomeClass[42] ;
      Object[][] oo = new OtherClass[23] [2] ;
      Object[][][] ooo = new OtherClass[23] [2] [9] ;
      o = oo = ooo;     // this is save to do,
                                   //because "n-dimensional" object-arrays
                                  // are just arrays of  other arrays, down to simple array
    pointer = o;         // ok, we are referencing o via Object "pointer"6. but, you cannot do this with primitive types:
      int[]  i1 = new int [99] ;
      int[][] i2 = new int [1] [3] ;
      i1 = i2                  // terror: impossible. this is awful, if you ask me.
                                   // ok, one could talk about "special cases" and
                                   // "the way the VM works", but this is not of interest to me as
                                   // a programmer. i'm not happy with that array-mess!
      pointer = i2;       // now this is completely legal. i2, i1 etc is an object!7. after the preparation, let's get into my main trouble (you have the answer, i know!) :
    suppose i have a class, with methods that should process ANY kind of object given. and - i don't know which. i only get it at runtime from an unknown source.
    let's say: public void BlackBox( Object x );
    inside, i know that there might be regular objects or arrays, and for this case i have some special hidden method, just for arrays... now try to find it out:
    public void BlackBox( Object x )
      if ( x == null)
           return;
       Class c = x.getClass();
       if ( c.isArray() )
              // call the array method if it's an array.........
              BlackBoxes(     (Object [] )  x );         // wait: this is a cast! and it WILL throw an exception, eventually!
              return;
       else
               DoSpecialStuffWith( x );
    }ok ? now, to process any kind of array, the special method you cannot reach from outside:
    private void BlackBoxes( Object[] xs )
       if ( xs != null )
            for ( Object x : xs )
                 BlackBox( x );
    // this will end up in some kind of recursion with more than one array-dimension, or when an Object[] has any other array as element!this approach is perfectly save when processing any (real) Object, array or "multi-dimensional" arrays of Objects.
    but, you cannot use this with primitive type arrays.
    using generics wouldn't help, because internally it is all downcasted to Object.
    BlackBox( new Integer(3) ) ---- does work, using a wrapper class
    BlackBox( new Integer[3] ) ----- yep!
    BlackBox( 3 ) ---- even this!
    BlackBox( new int[42] ) ---- bang! ClassCastException, Object[] != int[]
    i'm stuck. i see no way to do this smoothly. i could write thousands of methods for each primitive array - BlackBox( int[] is ) etc. - but this wouldn't help. because i can't cast an int[][] to int[], i would also have to write countless methods for each dimension. and guess, how much there are?
    suppose, i ultimately wrote thousands of possible primitive-type methods. it would be easy to undergo any of it, writing this:
    BlackBox( (Object) new int[9] [9] );
    the method-signature would again only fit to my first method, so the whole work is useless. i CAN cast an int[] to Object, but there seems no convenient way to get the real array out of Object - in a generic way.
    i wonder, how do you write a serialisation-engine? and NO, i can't rely on "right usage" of my classes, i must assume the worst case...
    any help appreciated!

    thanks, brigand!
    your code looks weird to me g and i think there's at least one false assumption: .length of a multidimensional array returns only the number of "top-level" subarrays. that means, every length of every subarray may vary. ;)
    well i guess i figured it out, in some way:
    an int is no Object;
    int[ ] is an Object
    the ComponentType of int [ ] is int
    so, the ComponentType of an Object int[ ] is no Object, thus it cannot be casted to Object.
    but the ComponentType of int [ ] [ ] IS Object, because it is int [ ] !
    so every method which expects Object[], will work fine with int[ ] [ ] !!
    now, you only need special treatment for 1-dimensional primitive arrays:
    i wrote some code, which prints me everything of everything:
        //this method generates tabs for indentation
        static String Pre( int depth)
             StringBuilder pre = new StringBuilder();
             for ( int i = 0; i < depth; i++)
                  pre.append( "\t" );
             return pre.toString();
        //top-level acces for any Object
        static void Print( Object t)
             Print ( t, 0);
        //the same, but with indentation depth
        static void Print( Object t, int depth)
            if ( t != null )
                 //be shure it is treated exactly as the class it represents, not any downcast
                 t = t.getClass().cast( t );
                if ( t.getClass().isArray() )
                     //special treatment for int[]
                     if ( t instanceof int[])
                          Print( (int[]) t, depth);
                     // everything else can be Object[] !
                     else
                          Print( (Object[]) t, depth );
                     return;
                else
                    System.out.println( Pre(depth) + " [ single object:] " + t.toString() );
            else
                System.out.println( Pre(depth) + "[null!]");
        // now top-level print for any array of Objects
        static void Print( Object [] o)
             Print( o, 0 );
        // the same with indentation
        static void Print( Object [] o, int depth)
            System.out.println( Pre(depth) + "array object " + o.toString() );
            for ( Object so : o )
                    Print( so, depth + 1 );
        //the last 2 methods are only for int[] !
        static void Print( int[] is)
             Print( is, 0 );
        static void Print( int[] is, int depth)
            System.out.println( Pre(depth) + "primitive array object " + is.toString() );
            // use the same one-Object method as every other Object!
            for ( int i : is)
                 Print ( i, depth + 1 );
            System.out.println( "-----------------------------" );
        }now, calling it with
    Print ( (int) 4 );
    Print ( new int[] {1,2,3} );
    Print( new int[][] {{1,2,3}, {4,5,6}} );
    Print( new int[][][] {{{1,2,3}, {4,5,6}} , {{7,8,9}, {10,11,12}}, {{13,14,15}, {16,17,18}} } );
    Print( (Object) (new int[][][][] {{{{99}}}} ) );
    produces this fine array-tree:
    [ single object:] 4
    primitive array object [I@9cab16
          [ single object:] 1
          [ single object:] 2
          [ single object:] 3
    array object [[I@1a46e30
         primitive array object [I@3e25a5
               [ single object:] 1
               [ single object:] 2
               [ single object:] 3
         primitive array object [I@19821f
               [ single object:] 4
               [ single object:] 5
               [ single object:] 6
    array object [[[I@addbf1
         array object [[I@42e816
              primitive array object [I@9304b1
                    [ single object:] 1
                    [ single object:] 2
                    [ single object:] 3
              primitive array object [I@190d11
                    [ single object:] 4
                    [ single object:] 5
                    [ single object:] 6
         array object [[I@a90653
              primitive array object [I@de6ced
                    [ single object:] 7
                    [ single object:] 8
                    [ single object:] 9
              primitive array object [I@c17164
                    [ single object:] 10
                    [ single object:] 11
                    [ single object:] 12
         array object [[I@1fb8ee3
              primitive array object [I@61de33
                    [ single object:] 13
                    [ single object:] 14
                    [ single object:] 15
              primitive array object [I@14318bb
                    [ single object:] 16
                    [ single object:] 17
                    [ single object:] 18
    array object [[[[I@ca0b6
         array object [[[I@10b30a7
              array object [[I@1a758cb
                   primitive array object [I@1b67f74
                         [ single object:] 99
    -----------------------------and i'll have to write 8 methods or so for every primitive[ ] type !
    sounds like a manageable effort... ;-)

  • Dynamic class loading and Casting

    Hi guys,
    spent lots of time trying to figure out how to do one thing with no luck, hope anybody can help me here. Here is what I have:
    I need to create a new object, I have dynamic variable of what kind of an object I need:
    sObjectType = "Article";
    ItemObject oItem = Item.init(1000, 1);           
    oItem.ArticleObjectCall();                      // ERROR is here, method does not exist, ArticleObjectCall is method of the Article classItem is a static Class that inits objects
    public class Item {
         public static ItemObject init(String sObjectType) {
                  ItemObject oClass = Class.forName("com.type." + sObjectType).newInstance();
                  return oClass;
    }Below are the 2 classes Article and ItemObject
    Article
    package com.type;
    public class Article extends ItemObject {     
         public void ArticleObjectCall() {
              System.out.println("Article Hello");
    ItemObject
    public class ItemObject {
         public ItemObject() {          
    }

    Ajaxian wrote:
    This is a method INIT, I am dynamically including class com.type.Article , Article extends ItemObject, I am casting new instance of Article to (ItemObject) to return a proper type but later when I try to call oClass object which is I believe my Article class, I get an error. None of which answers my question, yet it does show that you are thoroughly confused...
    String x = "blub";
    Object y = x;
    System.out.println(y.length); // We both know y is a string, but the compiler does not. => ErrorThe compiler enforces the rules of a static type system, your question is quite explicitly about dynamism, which is not without reason the antonym to statics. If you load classes dynamically, you need to use reflection to invoke their methods.
    With kind regards
    Ben

  • ORA-22905 and Cast function

    I am running a query with following code:
    select d.acct_num, lib.fmt_money(a.amt) Total Amount
    from account d, table(report.lib.expense (d.acct_num)) a
    where clause.
    Here:
    1. Report is another schema containing packqges for reporting development.
    2. lib is package name created in the report schema. It contains function such as expense.
    3. expense is a function under Lib package as
    function expense (p_acct number) return number is
    acct_num number;
    begin select xxxx into acct_num from xxx_table); return nvl(acct_num, 0);
    end expense;
    Then when I run this select statement, it gave me ORA-22905 error. Cause: attempt to access rows of an item whose type is not known at parse time or that is not of a nested table type. Action: use CAST to cast the item to a nested table type.
    I used CAST like this:
    select d.acct_num, CAST(a.amt as number ) Total Amount
    from account d, table(report.lib.expense (d.acct_num)) a
    where clause.
    It gave me ORA-00923 From keyword not found where expected.
    Please help me to find where the problem is and thank you for your help a lot.

    citicbj wrote:
    I have checked function and found that function was defined as this:
    function expense (p_exp varchar2) return number
    is
    l_exp number;
    begin
    select xxx into l_exp from xxxx where clause;
    return nvl(l_exp, 0);
    end expense;
    So this is not defined as the table of array. So I take the table off from select statement as
    select d.acct_num,
    to_number(a.amt) Total Amount
    from account d,
    report.lib.expense (d.acct_num) a
    where d.acct_num = a.acct_num;
    Then it return ORA-00933 SQL command not ptoperly ended. However, I couldn't see any not properly ended SQL code here. Please advise your comments.Should just be ...
    select
       d.acct_num,
       report.lib.expense (d.acct_num) as "Total Amount"
       --to_number(a.amt) Total Amount
    from account dNotice that i enclosed the column alias (Total Amount) in " ... that is because you can't have a column alias with spaces as you tried without doing this (the parser gets sad).
    Also, you cannot use a function returning a single value like this as a nested table (at least not the way you are trying) and in your case there's no reason. You don't want to join to it, you are passing in ACCT_NUM which the function will presumably use to filter out not relevant data.
    Finally, there's no reason to TO_NUMBER the function result ... it's already defined to return a number :)

  • How to test and cast an object to a generic

    Hi all,
    my problem is the following:
    I have a list of notifications from a transaction listener of the Eclipse Modeling Framework.
    Each element of that list is of type Notification, but I have to cast it to something else to work with it since it is pretty useless by itself.
    I need to test if it is a certain generic type (+NotifyingListImpl<?>+) but of course I can't use the instanceof test. Is there a way to solve the problem?
    Bear in mind that I googled a lot and tried a lot of solutions without success before asking this question (which I hope it is a piece of cake for an
    java expert :-) )
    As a side problem I don't know the actual type of the generic since I gathered all the information using the Eclipse debug, and the debug
    says my notification is of type NotifyingListImpl$1, I figured out the parameter of that type is ResourceImpl since the inspection of the
    notification's list of fields contains a this$0 of that type. Is my intuition about the Eclipse debug correct?

    I need to test if it is a certain generic type (+NotifyingListImpl<?>+) but of course I can't use the instanceof test.Yes you can:
    if (object instanceof NotifyingListImpl) { ... }
    As a side problem I don't know the actual type of the genericYou can't. It is erased to the lower bound at compile time.
    since I gathered all the information using the Eclipse debug, and the debug
    Is my intuition about the Eclipse debug correct?It has nothing to do with Eclipse debug. The information isn't available. It was erased by the compiler.

  • I need clarification regarding REFERENCE TYPES and CASTING.

    Hello all,
    I'm taking a course on the fundamental of JAVA. Everything's been going smoothly until I slammed into the the concept of CASTING and REFERENCE TYPES. Flat--out == I DON'T GET IT?
    I'm having trouble with...
    CONVERTING REFERENCE TYPES
    CASTING BETWEEN REFERENCE TYPES
    WORKING WITH REFERENCE TYPES
    I understand what's happening from an academic vantage point. I just don't understand why you'd want to convert REFERENCE TYPES? What would be an application of such an exercise?
    1. What IS a REFERENCE TYPE -- exactly?
    a. what are we referencing?
    b. type? type of what??
    for example... why would you want to do a widening conversion, a conversion of the hierarchy tree?
    I understand the concept of OBJECTS, CLASSES, METHODS and CONSTRUCTORS so far...
    I think it's the terminology that's screwing my up.
    Thanks,
    Alex

    ok... wow, thanks J.
    So--in a nutshell-- we're making it so that different
    objects:
    ie,. ford(), chevy(), honda(), lotus() and
    dealers()... so and so forth()...
    all share the resources(for lack of a better word) of
    the Auto Class? because all of those auto brand
    objects and one redically different object can be
    unrelated, correct?Um, yes and no.
    I just ran with the example you had, but that probably included too many concepts and they got muddied up.
    Yes, Chevy, Ford etc. all share the characteristics of Auto, since they're all subclasses. But that's just inheritance, and has nothing to do with casting.
    A "reference type" can loosely be described as a variable that refers to an object. (Constrasted with "primitive types" which are int, char, float, etc. and don't refer to objects--they just hold values.)
    Casting just tells the compiler that even though as far as it knows you only have a reference to some superclass, the object that reference points to will in fact be an instance of a subclass, and so treat it as such (e.g., we can now call methods that the subclass has that the superclass lacks).
    (You can also cast primitives, but one thing at a time.)
    So let's say you have class A (which extends object) and B extends A.
    A a = new B();
    B b = a; // won't compile. compiler sees the "A a" on the left of the =, not "new B()" on the right.
    B b = (B)a; // works because we're telling the compiler, "Dude, I'm seriously. This is a B.
    Note that if we had done new A() instead of new B(), it would still compile--the compiler would trust us. But at runtime, we'd get a ClassCastException, since we wouldn't actually have a B object.
    /**folks, I'm a web designer that has to learn Java
    so that I can perform my duties as a JSP author here
    at work. I tried to learn JSP sans Java and that was
    a simple exercise in ignorance.-- it's really hard
    without understanding the root concepts of Java and
    for that matter, C. Concepts like "polymorphism,
    inheritance, object references... are completely
    foreign to me. **/It's a rather big leap from web designing to OO concepts. Take your time, and don't be discouraged if you feel completely confused. It's a prerequisite. :-)

  • Parent class and Casting

    Hi all,
    I need to store different classes in a Vector. The classes have in common that they are all different views (MVC!). If I make a common parent, can I cast to that parent without problems?
    Background:
    I'm programming on a mobile, which uses different screens (choice screen, data screen and help screen). Depending on an event, be it a button pressed, or data comming in from another mobile, the view the player gets needs to be changed. The Model will call an update () method on the view. If I make the update method abstract, the update method of the child class will be used?
    Maik

    I need to store different classes in a Vector. The
    classes have in common that they are all different
    views (MVC!). If I make a common parent, can I cast
    to that parent without problems?Yes.
    If I make the update
    method abstract, the update method of the child class
    will be used? Is there any other? It will always use the method the instance implements.

  • Question about inheritance and  casting

    according to the java api it said Calendar() is a super-class of GregorianCalendar(). with that said it means GC inherits all members of C(). i hope everyone agrees with me here.
    why is it necessary to do this:
    Calendar c = new GregorianCalendar();//by the way this is called implicit casting per the java tutorial.if GC inherits everything from C, and if you need members from both classes, then wouldn't it be enough to just do
    GregorianCalendar gc = new GregorianCalendar();why is it necessary to declare a variable of the parent class and assign a subclass reference to that variable?

    then why does the tutorial show this?Why not? It's legal Java. It's what I would probably write, unless I knew I was going to use some methods that were in GregorianCalendar and not in Calendar.

  • Working with Subclasses and casting

    Hi,
    I was going through these three lines of code:
    Employee[] staff = new Employee[3];
    Manager boss = new Manager("Carl Cracker", 75000, new Day(1987,12,15));
    staff[0] = boss;
    Now this is probably familiar to readers of Horstmann and Cornell's Volume 1 CORE JAVA
    The book says that the compiler will consider staff[0] to be of type Employee even though we're assigning boss to it -- which is understandable.
    But to consider staff[0] to be of type Manager we have to cast it as shown:
    Manager boss = (Manager)staff[0];
    Now the compiler considers staff[0] to be of type Manager -- that's understandable too!!!
    But my question is -- does it really work that way?? -- I have my doubts -- could anyone explain this to me in a slightly more lucid manner -- the book gets a little confusing!!!
    Thanx,
    TheJavaKid

    Yes, that's how it works. Every object contains the properities of it's parent objects. something like this:
    [ Object ]
    [ Employee ]
    [ Manager ]
    The object you created was a Manager by reference, but it's also an Employee and an Object. If you have a handle to an Employee, you would have to downcast because it MIGHT be a Manager. If it's not a manager, then a ClassCastException will be thrown. Hope this helps a bit.

  • Help building an object, setting it in a session variable and casting

    Hi all,
    I have a problem that I hope you can help me with. The application I am working on has a simple MVC design architecture. The problem occurs when a request is made from the application to the controller servlet. The controller servlet looks at the request type and delegates the processing to the appropriate action and model classes. The model class returns an object of a specific class type that is put into the session variable. This session variable is then cast to the appropriate class type in the jsp that renders that class. The problem is that this particular class type has an array of another class type. The array is filled in the class constructor, but is null when returned to the controller.
    At run time when accessing the array I get a NullPointerException error. I can't seem to figure this one out. Any help is greatly appreciated.
    Here's the code:
    Controller DoPost method. The 'Action' objects are defined and initialized in the init() method.
            public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException{
                    try {
                            HttpSession session = request.getSession();
                            MemberProfileTbl memProf = (MemberProfileTbl)session.getAttribute("Member");
                            RequestDispatcher rd;
                            if (!validateUser(memProf, session)){
                                    session.setAttribute("LoginStatus", "Session Expired");
                                    rd = getServletContext().getRequestDispatcher("/LoginFail.jsp");
                                    rd.forward(request, response);
                                    return;
                            String act = getAction(request);
                            Action action = (Action)actions.get(act);
                            Object result = null;
                            try {
                                    result = action.perform(request, memProf);
                            }catch (NullPointerException npx) {
                                    npx.printStackTrace();
                            session.setAttribute("currObject", result);
                            rd = getServletContext().getRequestDispatcher("/test/MemberConsole.jsp");
                            rd.forward(request, response);
                    catch (Exception ex){
                            ex.printStackTrace();
    Action class:
            package accolo.actions;
            import javax.servlet.http.*;
            import accolo.model .*;
            import accolo.view.*;
            import accolo.db.MemberProfileTbl;
            public class ChangeMainView extends Action {
                    public String getName() {return "changeMainView";}
                    public Object perform(HttpServletRequest request, MemberProfileTbl memProf)
                            throws Exception, ClassNotFoundException, InstantiationException, IllegalAccessException{
                            Object result;
                            HMMainView hmMain = new HMMainView(memProf.email);
                           result = hmMain;
                           return result;
    HMMainView.java class
    public class HMMainView
            private HMMainViewJob[] jobs;
            public String test;
            public HMMainView(String email)
               HMJobsBean hmJobsBean = new HMJobsBean();
               JobTblDao jobTblDao = new JobTblDao();
               test = "test in constructor";
               try{
                 JobTbl[]  hmJobs = jobTblDao.getHMOpenJobs(email);
                 for(int j = 0; j < hmJobs.length; j++){
                            this.jobs[j].jobTitle = hmJobs[j].optionalTitle;
                            this.jobs[j].city = hmJobs[j].city;
                            this.jobs[j].state = hmJobsBean.getState(hmJobs[j].zipCode);
                            Hashtable counts = hmJobsBean.getJSCountsByStatus(hmJobs[j].jobId);
                            this.jobs[j].unranked = (String)counts.get("CANUNRANKED");
                            this.jobs[j].interviews = (String)counts.get("HMRI");
                            this.jobs[j].ranked = (String)counts.get("CANRANKED");
                            long closed = Long.parseLong((String)counts.get("HMRNI"));
                            closed += Long.parseLong((String)counts.get("HMCH"));
                            closed += Long.parseLong((String)counts.get("HMNH"));
                            this.jobs[j].closed = Long.toString(closed);
                }catch(Exception ex){
                    ex.printStackTrace();
            public HMMainViewJob[] getJobs(){ return jobs; }
    HMMainViewJob.java class
    package accolo.model;
    public class HMMainViewJob
            public long jobId;
            public String jobTitle;
            public String status_id;
            public String city;
            public String state;
            public String unranked;
            public String interviews;
            public String ranked;
            public String closed;
            public HMMainViewJob()
    Snippet of JSP that uses the code
      Object result = session.getAttribute("currObject");
      if (result != null){
        String className = result.getClass().getName();
        if (className.equals("accolo.model.HMMainView")){
               header = "HM/HMConsoleHeader.jsp";
               subNav = "HM/HMConsoleSubNav.jsp";
               user = "HM/HMConsoleUser.jsp";
               left = "HM/HMConsoleLeft.jsp";
    //           body = "HM/HMConsoleHome.jsp";
               HMMainView hmMain = (HMMainView) result;
               HMMainViewJob[] jobs = hmMain.getJobs();
              for (int i = 0; i < jobs.length; i++){
    %>
                    Jobs: <%=jobs.jobTitle%>
    <%

    I have not run this through a debugger yet. I don't have immediate access to a debugger to run it through, most of the development is simply done in vi. I was hoping any problem in the code would jump out at someone. I've been staring at it too long.
    I'll try to get a debugger set up.
    Thanks

  • Inheritance and casting

    Hi,
    I defined interfaces as follows:
    interface A {
    string name ();
    interface B : A {
    string b_method ();
    interface C : A {
    string c_method ();
    interface D {
    A create_object(in long type);
    I've generated java code, and implemented interfaces B, C and D. The interface D is implemented so that when someone calls create_object() method with parameter type=0, it returns an interface B object, and otherwise it returns an interface C object.
    My server application creates an object that implements interface D, and registers it with the nameserver .
    My client application gets the interface D object, and calls its create_object() method with various parameters, and gets its return object that is either the object instance of interface B or C.
    My problem is that I can't discover is this an object of interface B or C. When I check the class type, it always returns the interface A class, and it can't be casted to B or C.
    Has anyone had the same problem ???
    I would appreciate any help or tip!
    Thanks,
    Sasa.

    My client application gets the interface D object, and
    calls its create_object() method with various
    parameters, and gets its return object that is either
    the object instance of interface B or C.Not exactly.
    The client gets a proxy (of type A) to a server-side object, which itself is of type B or C.
    All the client ORB library knows is that the proxy is of type A, since that's what interface D declares, so what else could he return you?
    My problem is that I can't discover is this an object
    of interface B or C.
    org.omg.CORBA.Object.is_a(String );
    When I check the class type, it always returns the interface A class,You mean, when you check with instanceof operator.
    and it can't be casted to B or C.No it can't : it must be narrowed: your IDL compiler must have generated BHelper and CHelper classes, wich contain method narrow().
    This method returns the stub object it is passed if it fulfills the condition, or return a new stub object of the appropriate type.
    Try:A aRef = dObject.create();
    if (aRef.is_a("yourModule::B")
    B bRef = BHelper.narrow(aRef);
    }You already know this construct since you have already narrow()ed the untyped reference you got from the naming service, haven't you?
    N.B.: I don't remeber off-hand the syntax for the String passed to is_a(), but it is the "scoped name" for the interface, that is, it must include the modules hierarchy.

  • FLEX3 : Repeater, databinding, and cast operator

    Hello,
    Having encountered problems using Repeater in our enterprise project, we have decided to process heavy tests on Repeater and databinding.
    And what we have discovered is amazing!
    Please copy paste this code, run the app and click on the button.
    <?xml version="1.0" encoding="utf-8"?>
    <mx:WindowedApplication xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical">
            <mx:Script>
            <![CDATA[
                import mx.collections.ArrayCollection;
                [Bindable]
                private var sourceArray:ArrayCollection = new ArrayCollection([
                             new SimpleBean(),
                             new SimpleBean(),
                             new SimpleBean()
                public function changeValue():void{
                    var objectToModify:SimpleBean = sourceArray.getItemAt(1) as SimpleBean;
                    objectToModify.displayedName="Binding works";
            ]]>
        </mx:Script>
        <mx:VBox>
            <mx:Repeater id="rp" dataProvider="{sourceArray}">
                <mx:Label text="{SimpleBean(rp.currentItem).displayedName}" color="green"/>
                <mx:Label text="{(rp.currentItem as SimpleBean).displayedName}" color="red"/>
            </mx:Repeater>
        </mx:VBox>
        <mx:Button click="changeValue()"/>
    </mx:WindowedApplication>
    Here is the SimpleBean class:
    package
        public class SimpleBean
            [Bindable]
            public var displayedName:String="A default name";
    Amazing, no? It seems that the 2 cast operators behave differently inside a Repeater, and one prevents databinding to be triggered...
    So my question is: is it a SDK bug, or does this difference have an explanation?

    Hi schioche,
    I think it is a bug in Flex 3.* SDK, confirmed the the same behaviour by me.
    This bug was fixed somehow in Flex 4 SDK, verified.
    If upgrading to Flex 4 SDK is not an option to you, then you can initiate binding manually via ActionScript, worked for me
    <?xml version="1.0" encoding="utf-8"?>
    <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical">
        <mx:Script>
            <![CDATA[
                import mx.collections.ArrayCollection;
                [Bindable]
                private var sourceArray:ArrayCollection = new ArrayCollection([
                    new SimpleBean(),
                    new SimpleBean(),
                    new SimpleBean()
                public function changeValue():void{
                    var objectToModify:SimpleBean = sourceArray.getItemAt(0) as SimpleBean;
                    objectToModify.displayedName="Binding works";
                    rp.executeBindings();
            ]]>
        </mx:Script>
        <mx:VBox>
            <mx:Repeater id="rp" dataProvider="{sourceArray}">
                <mx:Label id="labelA" text="{SimpleBean(rp.currentItem).displayedName}" color="green"/>
                <mx:Label id="labelB" text="{(rp.currentItem as SimpleBean).displayedName}" color="red"/>
            </mx:Repeater>
        </mx:VBox>
        <mx:Button click="changeValue()"/>
    </mx:Application>

Maybe you are looking for