从Object变量中恢复属性

时间:2014-03-29 04:57:36

标签: java object methods attributes

所以这是我的问题的背景。

我创建了一个单链表,其节点' attribute是一个Object变量,所以我可以存储来自不同类的对象。到目前为止一切都很好。

        public class Node 
    {

        Object data;
        Node next;

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

[...]    

}

我不知道如何从存储的对象中恢复属性/方法。例如,这个。

public class Product 
{
    double discount;
    double price;

    public double getPrice() {
        return price;
    }

[...]

帮助。

2 个答案:

答案 0 :(得分:0)

您可以通过几种不同的方式获得这些。

Apache提供了一个很好的API, Java Reflection Beans Property API

或者您可以使用Java Reflection http://www.mkyong.com/java/how-to-use-reflection-to-call-java-method-at-runtime/

答案 1 :(得分:0)

另一种方法是,如果您存储的对象类型数量有限(或者至少计划从中检索属性),则使用instanceof和类强制转换

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
}