0

So this is the context for my question.

I created a singly linked list whose nodes' attribute is an Object variable so i can store objects from different classes. So far so good.

        public class Node 
    {

        Object data;
        Node next;

        public Node(Object data)
        {
            this.data=data;
            this.next=null;
        }

[...]    

}

Thing is i don't know how to recover attributes/methods from the stored objects. This one for example.

public class Product 
{
    double discount;
    double price;

    public double getPrice() {
        return price;
    }

[...]

Help.

2 Answers2

0

There are couple of different ways you can get these.

Apache provides a nice API , Java Reflection Beans Property API

or you can use Java Reflection http://www.mkyong.com/java/how-to-use-reflection-to-call-java-method-at-runtime/

Community
  • 1
  • 1
smk
  • 5,340
  • 5
  • 27
  • 41
0

Another way, if you have a limited number of types of objects that you are storing (or at least plan on retrieving attributes from) is to use instanceof and class cast as in

if(node.data instanceof Product){
    Product p = (Product) node.data;
    //Get attributes from products
else if(node.data instanceof SomethingElse){
    SomethingElse p = (SomethingElse) node.data;
    //Get attributes from somethingElse
}
...
else{
    //throw an error or ignore the final case
}
k_g
  • 4,333
  • 2
  • 25
  • 40