Receiving Objects of different classes??

Hi,
i have a little question...I know how to receive an ObjectMessage in JMS and how to retrieve the object from the message, but so far the message receiver knew what Object it is about to receive..and hence I used a cast like this:
Person p = (Person) objectmessage.getObject();
Now, I want, that the receiver does not know in advance what object it is about to receive....Does anybody have a good Idea??...Can I use something like this??
if (objectmessage.getClass().getName.equals("de.bla.Person"))
Person p = (Person) objectmessage.getObject();
Is this a good idea??...Ok. thanks...

it's probably better if you use an overloaded type and send this as the payload of your ObjectMessage.
e.g., inheritance relationships:
A <- B
A <- C <- D
Then you send and receive Objects of type A. There could be an overloaded method m (with different implementations according to which actual class the received object has). Like this you don't need explicit casts or class checks and let the JVM do the runtime type checking more efficiently and more object-oriented.

Similar Messages

  • When it's required to share a single object in different classes????

    Hi friends...
    I am new to java programming language....
    when it is required to share a single object in different classes???
    and
    please give me one example with explanation...
    Thank you
    regards Shree

    sun_shree wrote:
    Thanks for all giving reply.....
    please write the constructor which is accepting reference and please,,,,,, explain......
    Thanking youNo.
    This will be covered in any Java textbook or tutorial. Like this one: [http://java.sun.com/docs/books/tutorial/java/javaOO/arguments.html]
    After reading it and writing some code of your own to test your understanding, if you still have a specific question, post again.

  • Two equal objects, but different classes?

    When programming on binding Referenceable object with JDK version 1.5.0_06, I have encountered a very strange phenomenon: two objects are equal, but they belong to different classes!!!
    The source codes of the program bind_ref.java are listed as below:
    +++++++++++++++++++++++++++++++++++++++++++++++++++++++
    import java.lang.*;
    import java.io.*;
    import java.util.*;
    import javax.naming.*;
    import javax.naming.spi.ObjectFactory;
    import java.util.Hashtable;
    public class bind_ref {
    public static void main( String[] args ) {
    // Set up environment for creating the initial context
    Hashtable env = new Hashtable();
    env.put( Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.fscontext.RefFSContextFactory" );
    env.put( Context.PROVIDER_URL, "file:/daniel/" );
    Context ctx = null;
    File f = null;
    Fruit fruit1 = null, fruit2 = null;
    byte [] b = new byte[10];
    try {
    ctx = new InitialContext( env );
    Hashtable the_env = ctx.getEnvironment();
    Object [] keys = the_env.keySet().toArray();
    int key_sz = keys.length;
    fruit1 = new Fruit( "Orange" );
         SubReference ref1 = fruit1.getReference();
    ctx.rebind( "reference", fruit1 );
         fruit2 = ( Fruit )ctx.lookup( "reference" );
         System.out.println( "ref1's class = (" + ref1.getClass().toString() + ")" );
         System.out.println( "fruit2.myRef's class = (" + fruit2.myRef.getClass().toString() + ")" );
         System.out.println( "( ref1 instanceof SubReference ) = " + ( ref1 instanceof SubReference ) );
         System.out.println( "( fruit2.myRef instanceof SubReference ) = " + ( fruit2.myRef instanceof SubReference ) );
         System.out.println( "ref1.hashCode = " + ref1.hashCode() + ", fruit2.myRef.hashCode = " + fruit2.myRef.hashCode() );
         System.out.println( "ref1.equals( fruit2.myRef ) = " + ref1.equals( fruit2.myRef ) );
    } catch( Exception ne ) {
    System.err.println( "Exception: " + ne.toString() );
    System.exit( -1 );
    +++++++++++++++++++++++++++++++++++++++++++++++++++++++
    All the outputs are shown as below:
    =======================================================
    Fruit: I am created at Mon Jun 18 11:35:13 GMT+08:00 2007
    SubReference: I am created at Mon Jun 18 11:35:13 GMT+08:00 2007
    --------- (i)subref.hashCode() = (-1759114666)
    SubReference: I am created at Mon Jun 18 11:35:13 GMT+08:00 2007
    --------- (i)subref.hashCode() = (-1759114666)
    FruitFactory: obj's class = (class javax.naming.Reference)
    FruitFactory: obj's hashCode = -1759114666
    FruitFactory: obj = (Reference Class Name: Fruit
    Type: fruit
    Content: Orange
    FruitFactory: ( obj instanceof SubReference ) = false
    FruitFactory: subref_class_name = (Fruit)
    Fruit: I am created at Mon Jun 18 11:35:13 GMT+08:00 2007
    ref1's class = (class SubReference)
    fruit2.myRef's class = (class javax.naming.Reference)
    ( ref1 instanceof SubReference ) = true
    ( fruit2.myRef instanceof SubReference ) = false
    ref1.hashCode = -1759114666, fruit2.myRef.hashCode = -1759114666
    ref1.equals( fruit2.myRef ) = true
    ========================================================
    I hightlight the critical codes and outputs related to the strangeness with bold texts.
    Who can tell me what happens? Is it really possible that two objects belonging to different classes are equal? If so, why that?

    It can also depend on how you implement the equals method.
    class Cat {
        String name;
        Cat(String n) {
            name = n;
    class Dog {
        String name;
        Dog(String n) {
            name = n;
        public boolean equals(Object o) {
            return name.equals(o.name);
        public static void main(String[] args) {
            Dog d = new Dog("Fred");
            Cat c = new Cat("Fred");
            System.out.println(d.equals(c));
    }

  • How to access form objects from different class?

    Hello, I am new to java and i started with netbeans 6 beta,
    when i create java form application from template i get 2 classes one ends with APP and one with VIEW,
    i put for example jTextField1 with the form designer to the form and i can manipulate it's contents easily from within it's class (let's say it is MyAppView).
    Question>
    How can i access jTextField1 value from different class that i created in the same project?
    please help. and sorry for such newbie question.
    Thanks Mike

    hmm now it says
    non static variable jTree1 can not be referenced from static context
    My code in ClasWithFormObjects is
    public static void setTreeModel (DefaultMutableTreeNode treemodel){
    jTree1.setModel(new DefaultTreeModel(treemodel));
    and in Class2 it is
    ClasWithFormObjects.setTreeModel(model);

  • What's the best way to organize a sequence of objects of different classes

    Say I have a base class and some derived classes... lots of different derived classes, actually. I need to create many objects from all sorts of these subclasses and put them onto a LIFO sequence. What's the ideal type of collection to handle this? I'd also like to shuffle and pop elements, as well. I know about Vectors and Stacks, but I am wondering... Is it possible to have different types of these objects floating around in them? Would I have to use generics?
    I know you can create a list of the superclass and simply cast it to that, but I read that was bad practice.

    mhoribe wrote:
    I see.
    Let me ask you this. What, exactly, goes on when casting? If I add new methods and field to a subclass and cast it back to the base class, will I get any trouble using methods and fields? Or does Java simply allow this for simplicity sake. Like, we know it's a base class, but I'll allow you to call it a superclass just so it will be compatible and simple. Kinda get what I'm going for here?You never need to cast something to a super. Every instance of a subclass IS and instance of all its superclasses and interfaces.
    However, if you're adding new methods and fields to a subclass, there's a good chance you're subclassing for the wrong reasons, and especially if you're storing objects of these various classes in the same data structure but not treating them as a common parent type, you probably have a broken design.

  • Passing variables/objects to different classes

    I need to get the balance of bank accounts for the method "total" .
    Problem is I haven't written the class "Account" and therefore don't get to grips with it...
    Any ideas how I can get it to work?
    Thanks a lot
    class Account
        private double theBalance    = 0.00;   // Balance of account
        private String theName       = "";
        public Account( String name, double openingBalance )
          theBalance = openingBalance;
          theName    = name;
        public double getBalance()
          // assert theBalance >= 0.00;
          return theBalance;
        public String getName()
          return theName;
        public double withdraw( final double money )
          // assert theBalance >= 0.00;
          if ( theBalance >= money  )
            theBalance = theBalance - money;
            return money;
          } else {
            return 0.00;
        public void deposit( final double money )
          // assert theBalance >= 0.00;
          theBalance = theBalance + money;
      class BankStats {
           private Account accounts[];
          public BankStats(Account[] acc) {
               accounts = acc ;
          public double total (double ammount) {
               double bal = Account.getBalance(accounts);
         }

    Problem is I haven't written the class "Account" and therefore don't get to grips with it...Sorry, what's that stuff "class Account"? What do you mean you haven't written it? It's right there!
    Any ideas how I can get it to work?You haven't written Account in a such a way that you'll get the answer you want, but that's different.
    I do have an idea, but I'm not going to write it for you. Have a look at your total method. Does the compiler complain when you try to compile this? Something about static methods? Might want to read about that, and think about what that array of Accounts is really for. Maybe BankStats should loop over the array of Accounts and get their respective balances.
    When is your homework due?
    MOD

  • How to make versionable object of different class than Document?

    In the programmers reference is that every PublicObject can be versioned, but there are only samples for versioning documents. I would like to keep history on folder hierarchy changes, so I think I need a Folder that can be versioned.
    The question is how to do this?
    Should I override isVersionable method in subclass of Folder to return true?
    Please help

    Hi
    I am havin 10 text boxes in my application.
    But out of 10 , 3 will be always together(existence of one is not possible without the other two.)
    Now i want to create a vector of objects ( here object will consist of the value corresponding to these three boxes),there can be many elements in this vector.
    So i m thinking to make an inner class which have three String variables corresponding to these text boxes that exists together.
    What can b done ?

  • Sorting a list of different class objects

    Hi All ,
    How to sort a List a.which contains objects of different Classes, b. objects of same class . Is it possible to sort these by implementing Comparable interface .
    Thanks ,
    Rajesh Reddy

    rajeshreddyk wrote:
    Hi All ,
    How to sort a List a.which contains objects of different Classes, b. objects of same class . Is it possible to sort these by implementing Comparable interface .Well, if objects of different classes are kept in the same List and you want to sort them together they at least have that in common. They're Comparable-able. -:) To manifest that the different classes could all implement a Comparableable interface (or maybe Intercomparable would be a better choise of name.)

  • TestStand create different object for singleton class

    Hi all,
    we have a singleton class which has some functions used to do testing a harware.
    Our main Exe will create an object for that singleton class(which opens Com1 port and communicate with hardware). so the Exe will do basic communication test with hardware it is working well. We are using Teststand operator interface to do various testing by using sequence files. Main exe will use teststand usercontrols to execute tests when the user clicks Testbutton. after that, teststand try to create an object for that singleton but it returns new object not the existing one which is created by EXE. So it throwing me exeception "Com1 port access denied." (since we created object for signleton class @ very first in EXE)
    My question is Since that teststand runs in a separate Appdoamin will the singltonclass create separate object for different appdomain? if so is there any solution to reslove this?
    Hope i clearly explained my probs.
    Thanks in advance
    Srini 

    Hi Srini,
    How are you calling the executable?  From a Call Executable step?  Or are you using another means of calling it?   Also, why is TestStand trying to recreate the object?  As long as you have the correct handle to the object I don't think it matters what app domain you are in.
    Regards,
    jigg
    CTA, CLA
    teststandhelp.com
    ~Will work for kudos and/or BBQ~

  • While running my app I get the below error  - have different Class objects for the type javax/servlet/http/HttpServletRequest used in the signature

    I am running ATG[10.1.2] app on Jboss [EAP 5.1.0 GA] I am able to open dyn/admin however when I start my app I get the below error
    java.lang.LinkageError: loader constraint violation: when resolving method "atg.servlet.ServletUtil.setSessionConfNumCacheRequest(Ljavax/servlet/http/HttpServletRequest;)Ljavax/servlet/http/HttpServletRequest;" the class loader (instance of org/jboss/classloader/spi/base/BaseClassLoader) of the current class, atg/filter/dspjsp/PageFilter, and the class loader (instance of org/jboss/classloader/spi/base/BaseClassLoader) for resolved class, atg/servlet/ServletUtil, have different Class objects for the type javax/servlet/http/HttpServletRequest used in the signature
      at atg.filter.dspjsp.PageFilter.doFilter(PageFilter.java:215)
      at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
      at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
      at atg.servlet.ForwardFilter.doFilter(ForwardFilter.java:263)
      at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
      at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
      at atg.servlet.ErrorFilter.doFilter(ErrorFilter.java:279)
      at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
      at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
      at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:638)
      at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:446)
      at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:382)
      at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:310)
      at org.apache.catalina.core.StandardHostValve.custom(StandardHostValve.java:416)
      at org.apache.catalina.core.StandardHostValve.status(StandardHostValve.java:342)
      at org.apache.catalina.core.StandardHostValve.throwable(StandardHostValve.java:286)
      at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:141)
      at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
      at org.jboss.web.tomcat.service.jca.CachedConnectionValve.invoke(CachedConnectionValve.java:158)
      at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
      at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:330)
      at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:829)
      at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:598)
      at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447)
      at java.lang.Thread.run(Thread.java:680)
    11:22:47,413 ERROR [[localhost]] Exception Processing ErrorPage[errorCode=500, location=/global/errorPage500.jsp]

    The supported JBoss version for 10.1.2 is JBoss EAP 5.1.2 but I don't think that your issue is caused because of this. Your issue is more of an environmental thing as you are probably getting two different versions getting loaded of class javax.servlet.http.HttpServletRequest and so correspondingly two different Class objects as the error shows. One reason for this could be if you include any server-specific libraries (in present case the Servlet API JAR which contains the class javax.servlet.http.HttpServletRequest) of a different version in the /WEB-INF/lib of your web application. Try removing it from there if so and see if that helps.

  • Global object that will hold data acroos different Class

    Dear all,
    I have a funciton like generateRecord(userid,date,seqno). Now I want java to check whether the userid,date,and seqno had been used before. So I dicided to write the following code
    public Class UserRecord {
    private List userArray = new ArrayList();
    public addUserDetail ( UserDetail ud)
    {   this.userArray.add(ud);}
    Then I want to create a global variable object for the class UserRecord, because I want the object holds the user detail globally, I do that in another class
    public Class TestAbc {
    static public UserRecord ur;
    UserDetail ud;
    ur.userArray.add(ud);
    Is the above code exist any problem?

    Is the above code exist any problem?Did you tried running the program, it has many bugs?

  • Java receive files from different station ??

    Hi,
    I would like that a station can receive files from different stations in the same time.
    For that, I use multi-threading (with different socket TCP). I have just a problem, sometimes files received are empty or contains just the last line of file. I don't know why, I saw all datagrams on the network but at reception sometimes it reads just the end.
    The class to receive file functions when it receives just one file, but when files comes at the same time there are some problem.
    Is there a problem of thread ? (I start a thread but I don't know where stop it) or a problem in my class for receive file:
    For sending a file:
    while((len = fis.read(buffer,0,1024))!= -1)
              os.write(buffer, 0, len);
                   new LogFile().writeLogFileError     
    For receiveing file:
    while((len = is.read(buffer,0,1024))>=0)
    fos.write(buffer, 0, len);
    //when theres a problem, I receive -1 the first time, but I am sure data are sent to this station
    Is someone had same problem ?
    Thank you
    Maryline

    Maryline,
    its probably a better idea to use Stream Sockets, as opposed to datagrams, as the datagrams can be delivered in any order (hence end of file so soon possibly).
    On the Server Station do the following:
    import java.net.*;
    import java.io.*;
    private final int SERVER_PORT = 4567;
    private final int SERVER_BACKLOG = 100
    ServerSocket  server = new ServerSocket( SERVER_PORT, SERVER_BACKLOG );
    while (true) {
      Socket s = server.accept();
      //Start a new thread and pass the Socket s to it.
    }You also need to create ObjectInputStreams and ObjectOutputStreams to read and write the data
    ObjectInputStream input = new ObjectInputStream( s.getInputStream() );
    ObjectOutputStream output = new ObjectOutputStream( s.getOutputStream() );
    output.flush();On the client, you use
    Socket s = new Socket( SERVER_MACHINE_NAME, SERVER_PORT )
    ObjectOutputStream output = new ObjectOutputStream( s.getOutputStream
    output.flush();
    ObjectInputStream input = new ObjectInputStream( s.getInputStream() );
    () );You can then use
    output.writeObject( ANY_SERIALIZABLE_JAVA_OBJECT );to send the object, and
    JAVA_OBJECT_TYPE myObject = (JAVA_OBJECT_TYPE) input.readObject();to recieve the object.
    If its text data, you could read the data into a string field and send it
    I hope this gives you some ideas to hepl towards your solution
    Guy

  • Referencing fields between objects of same class

    Say I have created multiple TicketMachines from this class. Is there a way I create a method that uses "System.out.println" that would print the price of another TicketMachine object. And if so, could you please point me in the direction to find out how.
    * TicketMachine models a naive ticket machine that issues
    * flat-fare tickets.
    * The price of a ticket is specified via the constructor.
    * It is a naive machine in the sense that it trusts its users
    * to insert enough money before trying to print a ticket.
    * It also assumes that users enter sensible amounts.
    * @author David J. Barnes and Michael Kolling
    * @version 2006.03.30
    public class TicketMachine
        // The price of a ticket from this machine.
        private int price;
        // The amount of money entered by a customer so far.
        private int balance;
        // The total amount of money collected by this machine.
        private int total;
        //Creates a machine that issues tickets at a default price of 1000.
        public TicketMachine( )
         //Exercise 2.39  & 2.42(continues below)
          * By removing the parameter from this constructer
          * and setting the value of price to 1000, objects
          * from this class are automatically constructed with
          * a ticket price of 1000.
            price = 1000;
            balance = 0;
            total = 0;
        //Exercise 2.42
         * Create a machine that issues tickets of the given price.
         * Note that the price must be greater than zero, and there
         * are no checks to ensure this.
        public TicketMachine(int thePrice)
            price = thePrice;
            balance = 0;
            total = 0;
         * Return the price of a ticket.
        public int getPrice()
            return price;
         * Return the amount of money already inserted for the
         * next ticket.
        public int getBalance()
            return balance;
         * Receive an amount of money in cents from a customer.
        public void insertMoney(int amount)
            balance = balance + amount;
         * Print a ticket.
         * Update the total collected and
         * reduce the balance to zero.
        public void printTicket()
            // Simulate the printing of a ticket.
            System.out.println("##################");
            System.out.println("# The BlueJ Line");
            System.out.println("# Ticket");
            System.out.println("# " + price + " cents.");
            System.out.println("##################");
            System.out.println();
            // Update the total collected with the balance.
            total = total + balance;
            // Clear the balance.
            balance = 0;
        //Exercise 2.33
        //Prints "Please insert the correct amount of money." to the text terminal.
        public void prompt()
            System.out.println("Please insert the correct amount of money.");
        //Exercise 2.34
        //Displays the value of the price field in the text terminal.
        public void showPrice()
            System.out.println("The price of a ticket is " + price + " cents.");
        //Exercise 2.35
         * After creating two ticket machines with different prices
         * and calling thier showPrice methods it showed a different
         * output for each instance. This effect happenes because the
         * showPrice method prints out a string and the value of the price
         * field, which happens to be different in each instance, thereby
         * printing a different output.
        //Exercise 2.36
         * The result of System.out.println("# " + "price" + " cents.");
         * would print the string "# price cents." to the text terminal.
        //Exercise 2.37
         * The result of System.out.println("# price cents.");
         * would be the same as the result of exercise 2.36.
        //Exercise 2.40
        //This method is a mutator and takes no parameters
        //Empties the money form the ticket machine
        public void empty()
            total = 0;
        //Exercise 2.41
        //This method is a mutator
        //Changes the price of a ticket
        public void setPrice(int newPrice)
            price = newPrice;
    }

    Objects can refer to fields in other objects of the same class.
    It's not clear from your description what you're trying to accomplish, however.

  • How to use the different class for each screen as well as function.

    Hi Experts,
    How to use the different class for each screen as well as function.
    With BestRegards,
    M.Thippa Reddy.

    Hi ThippaReddy,
    see this sample code
    Public Class ClsMenInBlack
    #Region "Declarations"
        'Class objects
        'UI and Di objects
        Dim objForm As SAPbouiCOM.Form
        'Variables
        Dim strQuery As String
    #End Region
    #Region "Methods"
        Private Function GeRate() As Double
                Return Double
        End Function
    #End Region
    Public Sub SBO_Appln_MenuEvent(ByRef pVal As SAPbouiCOM.MenuEvent, ByRef BubbleEvent As Boolean)
            If pVal.BeforeAction = True Then
                If pVal.MenuUID = "ENV_Menu_MIB" Then
                End If
            Else ' Before Action False
                End If
        End Sub
    #End Region
    End Class
    End Class
    Rgds
    Micheal
    Vasu Anna Regional Feeling a???? Just Kidding
    Edited by: micheal willis on Jul 27, 2009 5:49 PM
    Edited by: micheal willis on Jul 27, 2009 5:50 PM

  • Assigning object of one class to object of another class.

    Hi,
    How will i assign an object of one class to an object of another class?
    Ex:
    ClassX A=some_method();
    Now how will I assign the object A of class ClassX to the object 'B' of another class 'ClassY'.

    In java you can only assign a object reference of one class into object reference of another class if the first class is the Second class (in other words the first class is a subclass of second class).
    for example if this is a inheritance chart
    Car ==========>Mercedes
    "===========>Audi
    then you can use
    Audi a1 = new Audi();
    Car c1 = a1;
    or Mercedes m1 = new Mercedes();
    Car c1 = m1;
    but not
    a1 = m1;
    before assigning a variable into another variable of different class, use:
    if(variable1 instanceOf ToBeAssignedIn Class){
    variable2 = variable1;
    example:
    Audi a1;
    Car c1;
    if(a1 instanceOf Car){
    c1 = a1;
    Edited by: gaurav.suse on Apr 10, 2012 1:14 PM
    Edited by: gaurav.suse on Apr 10, 2012 1:15 PM

Maybe you are looking for