Instanceof vs. enumeration

Which is considered to be better: using instanceof to determine a type of object at runtime or some sort of enumeration?
Thank you.

The problem is this: I have a series of objects that, logically, derive from a base class
public abstract class MyClass
    public abstract foo(MyClass obj);
}However, these classes interact with each other in different ways depending on what the class is:
public class MyChildClass1 extends MyClass
    private int j;
    public foo(MyClass obj)
        // default case
    public foo(MyChildClass1 obj)
        // do something in respect to MyChildClass1
    public foo(MyChildClass2 obj)
        // do something in respect to MyChildClass2
public class MyChildClass2 extends MyClass
    private int i;
    public foo(MyClass obj)
        // default case
    public foo(MyChildClass1 obj)
        // do something in respect to MyChildClass1
    public foo(MyChildClass2 obj)
        // do something in respect to MyChildClass2
}At this point, everything works out nicely. The problem is that when I try to store all of the objects into a Collection and call foo() with another object from the Collection, I lose the type of the object, and I call the wrong method.
In hindsight, I guess the real question is that would this be the best design? If not, what is wrong and how should I reapproach this problem.
Thank you again for your help!
Edited by: darkwraith on May 12, 2008 9:13 AM
Clarified code.

Similar Messages

  • Use enum or subclassing to differentiate between different elements?

    Hello all,
    I have a design decision to make.
    I have two different Elements with everything the same except the name.
    So I have two ideas on how this can be solved.
    1. Through subclassing.
    2. Through enumeration.
    I have tried to make two examples of this so you can recommend 1 or 2 only on a conceptual level not implementation.
    Sub classing
    public class Element {
         //Methods     
    public class A extends Element {
         //Nothing
    public class B extends Element {
         //Nothing
    public class Main {
         public static void main(String[] args) {
              Element elm = new A();
              if (elm instanceof A){}
              else if (elm instanceof B){}
    }Enumeration
    public class Element {
         public enum Type {A, B}
         private Type type;
         public Element(Type type) {
              this.type = type;
         public Type getType() {
              return type;
         //Methods
    public class Main {
         public static void main(String[] args) {
              Element elm = new Element(Type.A);
              switch(elm.getType()) {
                   case A:
                   case B:
    }Thanks /Farmor
    Edited by: Farmor on Dec 15, 2009 3:14 PM (Spelling error)

    Thanks for the answers.
    Then I will go with the enum solution that will give me a lot of free things.
    Such as I can limit the API user to only choose between my predefined values and the use of my API will be much easier when used in a good IDE.
    /Farmor

  • Instanceof + enumeration - can I use it this way?

    I use GWT. This framework allows to transfer Java objects from server (Java) to client (JavaScript) and back.
    So, the problem is:
    On the server-side comes ArrayList with Objects (classes: Hat, Glove, Food,Medicine) .
    All these classes are subclasses of GameItem.
    Hat, Glove are subclasses of Cloth.
    Cloth is also the subclass of GameItem.
    So, inheritance looks like:
    GameItem-> children:(*Cloth,* Food, Medicine)
    Cloth->children:(Hat,Glove)
    Server-side has enumeration:
    public enum CreatureGameItems {
        CreaturesClothes("clothes",new ru.gamedev.client.gameitem.Cloth().getClass()),
        CreaturesWeapon("weapon",new ru.gamedev.client.gameitem.Weapon().getClass()),
        CreatureToy("toys",new ru.gamedev.client.gameitem.Toy().getClass());
        CreatureGameItems(String itemName,Class javaClassOfItem){
            this.itemName = itemName;
            this.classOfItem = javaClassOfItem;
        private String itemName;   //keeps id of GameItemType
        private Class classOfItem;
        public String getItemName(){
            return this.itemName;
        public Class getStoredClass(){
            return classOfItem;
    } As you can see, my enum returns String value and Class associated with the member of enum.
    I want to do this thing:
    public boolean buySelectedGameItems(ArrayList<GameItem> inputList, int userId){
           System.out.println("BUYING ITEMS");
           for(int i=0; i<inputList.size(); i++){                       //go through all items
               for(CreatureGameItems c: CreatureGameItems.values()){    //go through all Items
                   if( (inputList.get(i) instanceof c.getStoredClass()) ){  //PAY ATTENTION TO THIS CODE LINE
                       System.out.println("item::: " + inputList.get(i).getClass() + "::: class ::: " + c.getStoredClass());
               }//CreatureGameItems
           }//i
           //&#1083;&#1091;&#1095;&#1096;&#1077; &#1087;&#1086;&#1083;&#1091;&#1095;&#1072;&#1090;&#1100; &#1086;&#1089;&#1090;&#1072;&#1090;&#1086;&#1082; &#1089;&#1095;&#1077;&#1090;&#1072; &#1087;&#1086;&#1083;&#1100;&#1079;&#1086;&#1074;&#1072;&#1090;&#1077;&#1083;&#1103; &#1080; &#1074;&#1086;&#1079;&#1074;&#1088;&#1072;&#1097;&#1072;&#1090;&#1100; &#1077;&#1075;&#1086;. &#1045;&#1089;&#1083;&#1080; &#1089; &#1074;&#1086;&#1079;&#1074;&#1088;&#1072;&#1090;&#1086;&#1084; &#1086;&#1073;&#1083;&#1086;&#1084;, &#1074;&#1099;&#1082;&#1080;&#1076;&#1086;&#1074;&#1072;&#1090;&#1100; &#1074;&#1089;&#1077; &#1085;&#1072;&#1093;&#1077;&#1088;
           return true;
       }I go through input Arraylist and my enum members. If I find equality between member and ArrayList object, I want to perform dome actions.
    I get such error: *")" expected*
    I understand, that my code is not right, but can I correct it and use enum
    Edited by: Holod on Dec 17, 2007 12:39 PM
    Edited by: Holod on Dec 17, 2007 12:49 PM
    Edited by: Holod on Dec 17, 2007 12:50 PM

    I found solution:
    for(int i=0; i<inputList.size(); i++){                      
               for(CreatureGameItems c: CreatureGameItems.values()){   
                   if(inputList.get(i).getClass() == (c.getStoredClass()) ){//check strict equality between classes
                       //perform my action
                       break;
                   if(inputList.get(i) instanceof Cloth) { //get children of Cloth class
                       //perform my action
                       break;
          }

  • Node removing in a Tree, for loop, and Enumeration

    Hi there
    it should be pretty easy, however i'm stuck with this code:
    public void supprNode(DefaultMutableTreeNode node){
    for(en = node.preorderEnumeration();e.hasMoreElements();){
    DefaultMutableTreeNode tmpNode= (DefaultMutableTreeNode) en.nexElement();
    if (tmpNode instanceof myderivedNodeClass)
        tmpNode.doSomething();
    if(!tmpNode.isRoot())
        removeNodeFromParent(tmpNode);
    }The problem is, the for loop doesn't traverse all the elements. That's if i call removeNodeFromParent. Is the enumeration updated twice?
    ie if my tree is
    root
    -1
    -2
    -3after the call of supprNode(root) i get:
    root
    -2And i really don't understand why.

    Hi!
    If you look at the apidoc of DefaultMutableTreeNode.preorderEnumeration() you will see following text:
    * Modifying the tree by inserting, removing, or moving a node invalidates
    * any enumerations created before the modification.
    So you should copy the elements of the enumeration in a separate list and iterate then over this list!
    With kind regard,
    Mathias

  • Will instanceof  work  in this case

    I am trying to simplify my code, and here is what i have
    i have the below classes :
    interface xyz
    class A implements xyz
    class B implements xyz
    i have lot of set/get methos in class A and class B. which are not in xyz.
    setfields(Obj) //this obj can be class A or class B
    Object ob=null;
    if ( obj instanceof A)
    ob=(A)obj;
    if(obj instanceof B)
    ob=(B)obj;
    //Here depending on the object i want to use set methods on that particular object. Is it possible?
    But when i do this , ob doesn't show the methods in Class A / class B.
    Am i doing the correct way.
    }

    I agree that's a good way to simplify your code, but you had a mistake
    in that...
    ob=(A)obj; // ob is a instance of Object
    because ob is just a object, so it can access only Object's method.
    you can correct code like this.
    A obj = (A)obj; // obj is a instance of Class A
    then, it can access any method in Class A.
    and I recommend make a 'int getType()' method in interface and
    use that. for example...
    interface xyx{
    public int getType();
    class A implements xyz
    public int getType(){return 0;}
    class B implements xyz{
    public int getType(){return 1;}
    setfields(xyz Obj) // this obj is must be instance of class implements xyz
    switch(Obj.getType()){
    case 0:
    A Obj2 = (A)Obj;
    break;
    case 1:
    B Obj2 = (B)Obj;
    break;
    you can make static int variable or enumeration class for more elegant code.
    I'm sorry about I can't explain well so that english isn't my mother tongue. -_-;;                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • Enumeration convertion in jsf

    Hi all
    I am about dealing with enumerations in my academic JSF project
    so, I have an entity Employee:
    package com.entities;
    import com.enumeration.Gender;
    import java.io.Serializable;
    import javax.persistence.Column;
    import javax.persistence.Entity;
    import javax.persistence.EnumType;
    import javax.persistence.Enumerated;
    import javax.persistence.GeneratedValue;
    import javax.persistence.GenerationType;
    import javax.persistence.Id;
    import javax.persistence.NamedQuery;
    @Entity
    @NamedQuery(name="Employee.findAll", query="SELECT e FROM Employee e")
    public class Employee implements Serializable {
        private static final long serialVersionUID = 1L;
        @Id
        @GeneratedValue(strategy = GenerationType.AUTO)
        private Integer id;
        @Column(name="nom", length=30)
        private String nom;
        @Enumerated(EnumType.STRING)
        @Column(length=1)
        private Gender gender;
        public Integer getId() {
            return id;
        public void setId(Integer id) {
            this.id = id;
        public String getNom() {
            return nom;
        public void setNom(String nom) {
            this.nom = nom;
        public Gender getGender() {
            return gender;
        public void setGender(Gender gender) {
            this.gender = gender;
        @Override
        public int hashCode() {
            int hash = 0;
            hash += (id != null ? id.hashCode() : 0);
            return hash;
        @Override
        public boolean equals(Object object) {
            // TODO: Warning - this method won't work in the case the id fields are not set
            if (!(object instanceof Employee)) {
                return false;
            Employee other = (Employee) object;
            if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
                return false;
            return true;
        @Override
        public String toString() {
            return "com.entities.Employee[ id=" + id + " ]";
    }the enumeration:
    * To change this template, choose Tools | Templates
    * and open the template in the editor.
    package com.enumeration;
    import java.io.Serializable;
    public enum Gender implements Serializable{
        M("Male"), F("Female");
        private String description;
        private Gender(String description) {
            this.description = description;
        public String getDescription() {
            return description;
    }and the index page that shows the list of employees:
    <?xml version='1.0' encoding='UTF-8' ?>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml"
          xmlns:h="http://java.sun.com/jsf/html"
          xmlns:f="http://java.sun.com/jsf/core"
          xmlns:p="http://primefaces.org/ui">
        <h:head>
            <title>Facelet Title</title>
        </h:head>
        <h:body>
            <f:view>
                <h:form>
                    <h1><h:outputText value="List"/></h1>
                    <h:dataTable value="#{employee.employees}" var="item" id="liste">
                        <h:column>
                            <f:facet name="header">
                                <h:outputText value="Id"/>
                            </f:facet>
                            <h:outputText value="#{item.id}"/>
                        </h:column>
                        <h:column>
                            <f:facet name="header">
                                <h:outputText value="Nom"/>
                            </f:facet>
                            <h:outputText value="#{item.nom}"/>
                        </h:column>
                        <h:column>
                            <f:facet name="header">
                                <h:outputText value="Gender"/>
                            </f:facet>
                            <h:outputText value="#{item.gender}"/>
                        </h:column>
                    </h:dataTable>
                            <h1><h:outputText value="Create/Edit"/></h1>
                            <h:panelGrid columns="2">
                                <h:outputLabel value="Nom:" for="nom" />
                                <h:inputText id="nom" value="#{employee.newEmployee.nom}" title="Nom" />
                                <h:outputLabel value="Gender:" for="gender" />
                                <h:selectOneMenu value="#{employeeBean.newEmployee.gender}" id="gender">
                                    <f:selectItem itemLabel="Male" itemValue="Male"/>
                                    <f:selectItem itemLabel="Female" itemValue="Female"/>
                                </h:selectOneMenu>
                            </h:panelGrid>
                            <h:commandButton value="ajouter" action="index.xhtml" actionListener="#{employeeBean.ajouter}" />
                        </h:form>
            </f:view>
        </h:body>
    </html>with the ejb associated( not included here)
    the problem I am facing is to convert the field selected in the selectOneMenu to an enumeration
    I did some search and I found that I have to add a converter class the faces-config.xml file, but still facing the same problem
    I am sure that I missed understood something with this but cannot detect what it is wrong with
    thanks for any help

    here is the log content after submitting the values:
    WARNING: Local Exception Stack:
    Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.2.0.v20110202-r8913): org.eclipse.persistence.exceptions.DatabaseException
    Internal Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry '1' for key 'PRIMARY'
    Error Code: 1062
    Call: INSERT INTO EMPLOYEE (ID, GENDER, nom) VALUES (?, ?, ?)
         bind => [3 parameters bound]
    Query: InsertObjectQuery(com.entities.Employee[ id=1 ])
         at org.eclipse.persistence.exceptions.DatabaseException.sqlException(DatabaseException.java:324)
         at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.executeDirectNoSelect(DatabaseAccessor.java:798)
         at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.executeNoSelect(DatabaseAccessor.java:864)
         at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.basicExecuteCall(DatabaseAccessor.java:583)
         at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.executeCall(DatabaseAccessor.java:526)
         at org.eclipse.persistence.internal.sessions.AbstractSession.basicExecuteCall(AbstractSession.java:1729)
         at org.eclipse.persistence.sessions.server.ClientSession.executeCall(ClientSession.java:234)
         at org.eclipse.persistence.internal.queries.DatasourceCallQueryMechanism.executeCall(DatasourceCallQueryMechanism.java:207)
         at org.eclipse.persistence.internal.queries.DatasourceCallQueryMechanism.executeCall(DatasourceCallQueryMechanism.java:193)
         at org.eclipse.persistence.internal.queries.DatasourceCallQueryMechanism.insertObject(DatasourceCallQueryMechanism.java:342)
         at org.eclipse.persistence.internal.queries.StatementQueryMechanism.insertObject(StatementQueryMechanism.java:162)
         at org.eclipse.persistence.internal.queries.StatementQueryMechanism.insertObject(StatementQueryMechanism.java:177)
         at org.eclipse.persistence.internal.queries.DatabaseQueryMechanism.insertObjectForWrite(DatabaseQueryMechanism.java:469)
         at org.eclipse.persistence.queries.InsertObjectQuery.executeCommit(InsertObjectQuery.java:80)
         at org.eclipse.persistence.queries.InsertObjectQuery.executeCommitWithChangeSet(InsertObjectQuery.java:90)
         at org.eclipse.persistence.internal.queries.DatabaseQueryMechanism.executeWriteWithChangeSet(DatabaseQueryMechanism.java:291)
         at org.eclipse.persistence.queries.WriteObjectQuery.executeDatabaseQuery(WriteObjectQuery.java:58)
         at org.eclipse.persistence.queries.DatabaseQuery.execute(DatabaseQuery.java:808)
         at org.eclipse.persistence.queries.DatabaseQuery.executeInUnitOfWork(DatabaseQuery.java:711)
         at org.eclipse.persistence.queries.ObjectLevelModifyQuery.executeInUnitOfWorkObjectLevelModifyQuery(ObjectLevelModifyQuery.java:108)
         at org.eclipse.persistence.queries.ObjectLevelModifyQuery.executeInUnitOfWork(ObjectLevelModifyQuery.java:85)
         at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.internalExecuteQuery(UnitOfWorkImpl.java:2842)
         at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1521)
         at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1503)
         at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1463)
         at org.eclipse.persistence.internal.sessions.CommitManager.commitNewObjectsForClassWithChangeSet(CommitManager.java:224)
         at org.eclipse.persistence.internal.sessions.CommitManager.commitAllObjectsWithChangeSet(CommitManager.java:123)
         at org.eclipse.persistence.internal.sessions.AbstractSession.writeAllObjectsWithChangeSet(AbstractSession.java:3766)
         at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.commitToDatabase(UnitOfWorkImpl.java:1404)
         at org.eclipse.persistence.internal.sessions.RepeatableWriteUnitOfWork.commitToDatabase(RepeatableWriteUnitOfWork.java:616)
         at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.commitToDatabaseWithChangeSet(UnitOfWorkImpl.java:1511)
         at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.issueSQLbeforeCompletion(UnitOfWorkImpl.java:3115)
         at org.eclipse.persistence.internal.sessions.RepeatableWriteUnitOfWork.issueSQLbeforeCompletion(RepeatableWriteUnitOfWork.java:331)
         at org.eclipse.persistence.transaction.AbstractSynchronizationListener.beforeCompletion(AbstractSynchronizationListener.java:157)
         at org.eclipse.persistence.transaction.JTASynchronizationListener.beforeCompletion(JTASynchronizationListener.java:68)
         at com.sun.enterprise.transaction.JavaEETransactionImpl.commit(JavaEETransactionImpl.java:437)
         at com.sun.enterprise.transaction.JavaEETransactionManagerSimplified.commit(JavaEETransactionManagerSimplified.java:867)
         at com.sun.ejb.containers.BaseContainer.completeNewTx(BaseContainer.java:5115)
         at com.sun.ejb.containers.BaseContainer.postInvokeTx(BaseContainer.java:4880)
         at com.sun.ejb.containers.BaseContainer.postInvoke(BaseContainer.java:2039)
         at com.sun.ejb.containers.BaseContainer.postInvoke(BaseContainer.java:1990)
         at com.sun.ejb.containers.EJBLocalObjectInvocationHandler.invoke(EJBLocalObjectInvocationHandler.java:222)
         at com.sun.ejb.containers.EJBLocalObjectInvocationHandlerDelegate.invoke(EJBLocalObjectInvocationHandlerDelegate.java:88)
         at $Proxy241.persist(Unknown Source)
         at com.sessionBeans.__EJB31_Generated__EmployeeFacade__Intf____Bean__.persist(Unknown Source)
         at com.beans.EmployeeBean.ajouter(EmployeeBean.java:37)

  • Enumerations in JPA

    Hi all
    I have a question about enumerations,
    class Test{
       public enum Gender{
         Male, Female
    @Enumerated(EnumType.STRING)
    @Column(length=1)
    private Gender gender;
    }my question is this correct?
    my goal is to keep only one character of the enumration
    thanks for help

    Hi guys,
    here is what I did according to your suggestions
    package com.entities;
    import com.enumeration.Gender;
    import java.io.Serializable;
    import javax.persistence.Column;
    import javax.persistence.Entity;
    import javax.persistence.EnumType;
    import javax.persistence.Enumerated;
    import javax.persistence.GeneratedValue;
    import javax.persistence.GenerationType;
    import javax.persistence.Id;
    import javax.persistence.NamedQuery;
    @Entity
    @NamedQuery(name="Employee.findAll", query="SELECT e FROM Employee e")
    public class Employee implements Serializable {
        private static final long serialVersionUID = 1L;
        @Id
        @GeneratedValue(strategy = GenerationType.AUTO)
        private Integer id;
        @Column(name="nom", length=30)
        private String nom;
        @Enumerated(EnumType.STRING)
        @Column(length=1)
        private Gender gender;
        public Integer getId() {
            return id;
        public void setId(Integer id) {
            this.id = id;
        public String getNom() {
            return nom;
        public void setNom(String nom) {
            this.nom = nom;
        public Gender getGender() {
            return gender;
        public void setGender(Gender gender) {
            this.gender = gender;
        @Override
        public int hashCode() {
            int hash = 0;
            hash += (id != null ? id.hashCode() : 0);
            return hash;
        @Override
        public boolean equals(Object object) {
            if (!(object instanceof Employee)) {
                return false;
            Employee other = (Employee) object;
            if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
                return false;
            return true;
        @Override
        public String toString() {
            return "com.entities.Employee[ id=" + id + " ]";
    package com.enumeration;
    public enum Gender {
        M("Male"), F("Female");
        private String description;
        private Gender(String description) {
            this.description = description;
        public String getDescription() {
            return description;
    }and it generates the table employee with the gender column as a varchar(1) witch is the desired result
    thanks a million for help
    best regards rashid

  • Problems with enumerated type and DataSocket

    I am publishing an enumerated type variable using DataSocket write and I am having problems subscribing to this with other clients on the network. I can get the program to work ok if I replace the enumerated type with a straight numeric or a Text Ring for example. Is there anything special I should be looking out for when using enumerated types in this type of application.
    Thanks Kelly

    Updating to the latest version of LabVIEw (6.0.2) should correct this problem:
    http://digital.ni.com/softlib.nsf/websearch/F983BDA17B8F401B862569EC005A11C2
    Also, I would suggest updating to the latest version DataSocket:
    http://digital.ni.com/softlib.nsf/web%2Fall%20software?OpenView&Start=1&Count=500&Expand=6#6
    Chris_Mitchell
    Product Development Engineer
    Certified LabVIEW Architect

  • Null value in List Binding (enumeration mode)

    Hi,
    how can I declare a NULL value in a List binding with enumeration mode?
    A user should be able to select an empty entry in a combobox to update an attribute with a null value.
    I'm using JDev9052 and JClient.
    Any hints?
    Thanks,
    Markus

    Adding '-1' in JComboBox (addItem(new Integer(-1))) or in the control binding does not change the picture. Sorry.
    While play with different List bindings I have discovered that a Button LOV Binding works when using a "select * UNION select null from dual" view object. It does not work with a Combobox LOV binding. Why?
    Still, my problem List binding in enumeration mode (with Combobox) is unsolved. any hints or samples?
    My current combobox binding:
    <DCControl
    id="Job"
    DefClass="oracle.jbo.uicli.jui.JUComboBoxDef"
    SubType="DCComboBox"
    BindingClass="oracle.jbo.uicli.jui.JUComboBoxBinding"
    IterBinding="EmpView1Iterator"
    ApplyValidation="false"
    isDynamic="false"
    ListOperMode="0"
    StaticList="true"
    Editable="false" >
    <AttrNames>
    <Item Value="Job" />
    </AttrNames>
    <ValueList>
    <Item Value="ANALYST" />
    <Item Value="CLERK" />
    <Item Value="MANAGER" />
    <Item Value="PRESIDENT" />
    <Item Value="SALESMAN" />
    <Item Value="-1" />
    </ValueList>
    </DCControl>
    My current Button LOV binding:
    <DCControl
    id="Job2"
    DefClass="oracle.jbo.uicli.jui.JULovButtonDef"
    SubType="DCLovButton"
    BindingClass="oracle.jbo.uicli.jui.JULovButtonBinding"
    IterBinding="EmpView1Iterator"
    DTClass="oracle.adf.dt.objects.JUDTCtrlListLOV"
    ApplyValidation="false"
    isDynamic="false"
    ListOperMode="0"
    ListIter="JobListView1Iterator" >
    <AttrNames>
    <Item Value="Job" />
    </AttrNames>
    <ListAttrNames>
    <Item Value="Job" />
    </ListAttrNames>
    <ListDisplayAttrNames>
    <Item Value="Job" />
    </ListDisplayAttrNames>
    </DCControl>

  • More fun with enumerated dropdowns - Binding to table

    Hi All,
    I'm having some trouble with enumerated dropdowns.
    My context is as follows:
    node DATA 1...1
    ---> node FLIGHTS 0...N
       -->CARRID etc from SFLIGHTS
    --->DDL (element type string)
    I have successfully tried to add a simple dropdown with the following code on the component controller:
    method wddoinit .
        data lo_nd_data type ref to if_wd_context_node.
        data lo_el_data type ref to if_wd_context_element.
        data ls_data type wd_this->element_data.
        data lv_ddl like ls_data-ddl.
        data node_info type ref to if_wd_context_node_info.
        data vals type table of  wdr_context_attr_value.
        data: s_element type wdr_context_attr_value.
        data: str type string.
    *   navigate from <CONTEXT> to <DATA> via lead selection
        lo_nd_data = wd_context->get_child_node( name = wd_this->wdctx_data ).
    *   get element via lead selection
        lo_el_data = lo_nd_data->get_element(  ).
        lo_el_data->get_static_attributes(
          importing
            static_attributes = ls_data ).
    *      get node info
        call method lo_nd_data->get_node_info
          receiving
            node_info = node_info.
         do 25 times.
           str = sy-index.
           condense str no-gaps.
           s_element-text = str.
           s_element-value = str.
           append s_element to vals.
        enddo.
    *    Set Value_sets to node_info
         call method node_info->set_attribute_value_set
          exporting
            name      = 'DDL'
            value_set = vals
    endmethod.
    This works fine, however now I am trying the same thing with a field from the SFLIGHTS table.
    I want to display a table of the retrieved SFLIGHTS but a field as a dropdown with valid entries from the database. I have added the following code to the view.
    method WDDOINIT .
        data lo_nd_data type ref to if_wd_context_node.
        data lo_nd_flights type ref to if_wd_context_node.
        data lo_el_flights type ref to if_wd_context_element.
        data ls_flights type wd_this->element_flights.
        data gt_flights type table of sflights.
        select * from sflights into table gt_flights.
    *   navigate from <CONTEXT> to <DATA> via lead selection
        lo_nd_data = wd_context->get_child_node( name = wd_this->wdctx_data ).
    *   navigate from <DATA> to <FLIGHTS> via lead selection
        lo_nd_flights = lo_nd_data->get_child_node( name = wd_this->wdctx_flights ).
        lo_nd_flights->bind_table( gt_flights ).
           types: begin of ty_carrname,
         carrname type s_carrname,
         end of ty_carrname.
       data: gt_carrname type table of ty_carrname.
       select distinct carrname
          from sflights
          into table gt_carrname.
         data lv_carrname like ls_flights-carrname.
         data node_info type ref to if_wd_context_node_info.
         data vals type table of  wdr_context_attr_value.
         data: s_element type wdr_context_attr_value.
         data: str type string.
          lo_nd_flights->get_static_attributes(
          importing
            static_attributes = ls_flights ).
          call method lo_nd_flights->get_node_info
          receiving
            node_info = node_info.
         field-symbols: <carrname> like line of gt_carrname.
         loop at gt_carrname assigning <carrname>.
           str = <carrname>-carrname.
           s_element-text = str.
           s_element-value = str.
           append s_element to vals.
         endloop.
         call method node_info->set_attribute_value_set
          exporting
            name      = 'CARRNAME'
            value_set = vals.
    endmethod.
    I can display all the entries with a repeating subform but when I bind the CARRNAME to an enumerated dropdown I get an ADS rendering error:
    WebDynpro Exception: The ADS call has failed. You can find information about the cause in the error.pdf on the application server
    I have looked in the Error PDF but it is blank.
    Does anyone have any suggestions on what is goign wrong or how to diagnose the problem.
    I am assuming you can have a data element that has a 0..N cardinality (i.e a table element) and is also of type enumerated dropdown.
    I'm guessing this is something to do with cardinality but I have no way to find out.
    Thanks,
    Gregor

    I have looked in the defaultTrace file and found the following errors:
    1.  A pdf document with 0 pages.
        Return Status: Render Failure
        Output Trace returned: <?xml version="1.0" encoding="UTF-8"?>
    <log>
       <m mid="29184" tid="10064.4896" sev="f" d="2008-11-12T15:20:01.722Z">Malformed SOM expression: $record.sap-vhlist.FLIGHTS\\.DATA[*]\\.CARRNAME.item[*]</m></log>
    Has anybody else used the enumerated dropdown element bound to dynamic data?
    I am using the latest releases and the "Specify Item Values" on the Object->Binding tab is filled in with what looks correct ($record.sap-vhlist.FLIGHTS\.Data etc) but greyed out.
    Thanks

  • How to read enumerated values from an OPC server via Datasocket

    Hi Labviewers,
    I am using LV8.2 and I am trying to find if it is possible to read enumerations from an OPC server via Datasocket, not just the values.
    I can successfully read a value for an OPC server via Datasocket and I get a value for example 3, is it possible to get the enumeration/string that corresponds to this value i.e. "Open".
    Many thanks in advance
    Dimitris

    Hi Sarah,
    With the input type as variant I get the following response:
    1                                     <-This is the current numeric value of the parameter
    4 Attribute(s):
       'Quality' -> 192
       'TimeHigh' -> 29861723
       'TimeLow' -> -665408304
       'Timestamp' -> 39.238E+3
    With the Input set to         Enum constant I get no values or strings coming back. With the Input set to                Ring constant I just get the numeric value   
    Dimitris   

  • Help with exporting document and generating an enumerated value error

    Can anyone help me figure out why I cannot get this script to export the document and save it for the web?
    I keep getting the same frustrating "Enumerated Value expected".
    here is the script thus far:
    * attempting to create a script to insert names automatically within photoshop cs2. Similar to the PSP.
    tag = app.activeDocument;
    var lee = ["Barb","Belle","Betty","Carmel","Christy","Connie",
    "Debbie","Debra","Denise","Diamond","Dolceluna","Irene","Jacqui"];
    //determine if active layer is a text layer or not.
    if(tag.isBackground == true){
    alert("this is a background layer and cannot be changed.");
    else{
    alert("this is the name layer.")
    for(i=0;i<lee.length;i++){
    tag.activeLayer.textItem.contents = lee[i];
    var options = new ExportOptionsSaveForWeb();
    options.format = SaveDocumentType.PNG-24;
    options.interlaced = false;
        options.PNG8= false;
    var fName = lee[i];
    var newName = fName+'-'+tag.name+'.png';
    alert(newName);
    //EXPORT DOCUMENT KEEPS GENERATING ENUMBERATED VALUE EXPECTED
    // web.matte = MatteType.NONE;
    tag.exportDocument(File(tag.path + '/' + newName),ExportType.SAVEFORWEB,options);
    } // closes for loop
    }// end of else statement

    Yes the guide is misleading. It says 'For this property, only COMPUSERVEGIF, JPEG, PNG-8, PNG-24, and BMP are supported.'
    It really should say 'For this property, only COMPUSERVEGIF, JPEG, PNG, and BMP are supported.'
    But if you look under SaveDocumentType you will not find PNG-8 or PNG-24 listed in the values.

  • Can I append the file name from a Foreach Loop Container Enumerator into a SQL Server Statement?

    I would like to pass back via an Email the name of the file that was successfully FTP'ed to a remote server. And I was hoping to do this via an Execute SQL Task with the following SQL Statement...but I just don't know if it will append the Foreach Loop Container
    variable enumerator to the appended Email message that I am building in SQL Server or if I can and how I can...
    I sort of get the feeling that I can try and do this via Dynamic SQL...I just don't know if by building dynamic SQL if my Foreach Loop Container enumerator variable will be appended to my Email Message via the SQL Server UPDATE 
    @[User::FTPFHFileName]
    Or do I add a Data Flow Task and an OLE DB Command and pass the Foreach Loop Container enumerator variable to a Stored Procedure referenced in the OLE DB Command via a "?"
    Thanks for your review and am hopeful for a reply.

    Hello,
    It seems that the issue had been solved and thanks for your sharing. It will be very beneficial for other community members who have similar questions.
    I’d like to mark this issue as "Answered". Please also feel free to unmark the issue, with any new findings or concerns you may have.
    Regards,
    Katherine Xiong
    Katherine Xiong
    TechNet Community Support

  • Switch statement with enumerated types

    Hello,
    I'm currently having problems (error in eclipse) using enums in a
    switch block. Eclipse says:
    "The enum constant Constants.AnalysisType.<each case> reference cannot be qualified in a case label.
    for each of the cases that I try to use the enumerated type. My code
    looks something like this:
    switch (analysisType) {
    case Constants.AnalysisType.NONE:
        break;
    case Constants.AnalysisType.MVGAVG:
        break;
    }(With a number of cases omitted).
    where analysisType is the enumerated type defined in
    a file called Constants.java.
    The class where the error is occuring is located at:
    package myprog.ui.ViewPanelTab; and the enumerated type is declared at:
    package myprog.utility.Constants;I have the required import statements in the ViewPanelTab class.
    I have tried
    public, private, public static, private static as modifiers on the enumeration.
    Any ideas as to why eclipse won't let me do this.
    Thanks for any help
    Devon

    Why is it that the entire switch and all of its cases have the same locality ?By "locality" do you mean "scope" (i.e. the inability to declare two variables with the same name)? I find it rather irritating that I can't write switch (foo)
        case bar:
            int quux = ...
            break;
        case baz:
            int quux = ...
            break;
    }My guess as to the reason for the decision to disallow this is that otherwise removing a break statement could create a compiler error where there previously was none, and that this would be confusing. It is possible to create a fresh scope, though, by using braces:switch (foo)
        case bar:
            int quux = ...
            break;
        case baz:
            int quux = ...
            break;
    }

  • Ora-00600 error when registering xsd with large enumeration

    I am trying to register the xsd:
    http://212.130.77.78/StandatWS/StandatXSD.asmx/GetSchema?SchemaFile=std00019.xsd
    It contains a very large enumerated type like this:
    <xsd:simpleType name="std00019">
    <xsd:annotation>
    <xsd:documentation>Stofparametre</xsd:documentation>
    </xsd:annotation>
    <xsd:restriction base="xsd:string">
    <xsd:enumeration value="0000">
    <xsd:annotation>
    <xsd:documentation></xsd:documentation>
    </xsd:annotation>
    </xsd:enumeration>
    <xsd:enumeration value="0001">
    <xsd:annotation>
    <xsd:documentation>Syn</xsd:documentation>
    </xsd:annotation>
    </xsd:enumeration>
    The file is more than 7000 lines of xml. If I try to cut it down to less than 4000 lines or so, then I can register it. Otherwise it give me an error like this:
    1 begin
    2 dbms_xmlschema.registerURI(
    3 'http://212.130.77.78/StandatWS/StandatXSD.asmx/GetSchema?SchemaFile=std00019.xsd',
    4 'http://212.130.77.78/StandatWS/StandatXSD.asmx/GetSchema?SchemaFile=std00019.xsd'
    5 );
    6* end;
    SQL> /
    begin
    FEJL i linie 1:
    ORA-00600: intern fejlkode, argumenter: [qmxiCreateColl2], [11], [], [], [],
    ORA-06512: ved "XDB.DBMS_XMLSCHEMA_INT", linje 0
    ORA-06512: ved "XDB.DBMS_XMLSCHEMA", linje 185
    ORA-06512: ved linje 2
    I am using 9.2.0.6.0
    Do you know if there is a maximum length of an enumeration in oracle?

    If you cannot post the schema please open a itar with oralce support so that the schema can be uploaded.

Maybe you are looking for

  • The 'preview' is interfering in our playing online games ... how can we turn it off ???

    Hi Uploaded the Firefox toolbar from my Photobucket account earlier today. We have been having trouble with our Internet Explorer for a while and my son prefers Firefox, so I thought I'd give it a try. My fiance' and I play DAILY on goldtoken.com ...

  • How to write on a new line ("\n") to a file

    I dont know how to write on a new line ... this method writes everything in long line. I tried doing pS.println("\n") before the pS.println(buffer.toString()); Some one please direct me :) public void WriteToFile() {      try {           byte[] recor

  • Wet iPhone/ Hard Reset

    My iPhone got wet on Thursday, from then on the sound wouldn't work other than calls, text tones, lock/unlock sounds, and keypad sounds didn't work at all. Then today it told me my phone has to be restored because i can't make or receive calls now. I

  • There has to be a little hope here:

    Lost contacts during 5.0 Upgrade, now have cloud on iphone. Started manually entering in all contacts and saving to the cloud.  I would like to know if I plug my phone into itunes would I be able to use "The restore from backup" feature without affec

  • MS Office report for servo motion controller

    Dear all, Good day, My application is servo motion controller where I will choose profile from tab deliminated text file. Attached VI working fine and I would like to add more features like MS office report where report will be generate after complet