Home > Enterprise >  Access Object1 methods from a returned Object
Access Object1 methods from a returned Object

Time:03-21

I have to make a list of objects, Object1, Object2, Object3.

class Object1 {
    private String str;
    private double num;
    
    public Object1(...){
    ...
    }

    public double getNum(){
        return this.num;
    }

    @Override
    public String toString(){
        return String.format(" String: %s, Number %.2f", this.str, this.num);
    }

}

In order to do this I created another class Item which, depending on the input of the constructor, initializes either Object1 or Object2 and so on and instantiate an access() method that returns said object.

class Item{
    private Object item;
    
    public Item(String str, double num){
        item = new Object1(str, num);
    }

    public Item(String str, double num, int num1){
        item = new Object2(str, num, num1);
    }

    ...

    public Object access(){
        return item;
    }
}

In the Main if I access the item toString it gives back the right output, but I cannot access any other methods of Object1 etc.

print(list.get(i).access().toString());

>>> String: Something, Number: 99.92

print(""   list.get(i).access().getNum());

>>> Cannot resolve method getNum() in Object

How can I do this properly?

CodePudding user response:

If you know that this is an Object1, you can cast it, like

print(""   ((Object1)list.get(i).access()).getNum());

If you don't know it's an Object1, you can use instanceof

if (list.get(i).access() instanceof Object1) {
  ...
}

Finally, in the case where you know nothing, there is a way introspect an Object's methods

list.get(i).access().getClass().getMethods();

CodePudding user response:

With Java 17, you can try this (with preview being activated):

…
switch( list.get( i ).access() )
{
  case Object1 object1 -> object1.getNum();
  case Object2 object2 -> object2. … // whatever method fits …
  case Object3 object3 -> object3. …
  case null -> throw new Error( "access() returned null" );
  default -> throw new Error( "No clue what accessed() returned …";
}

The keyword here is "pattern matching for switch", and I think it is a nice feature to solve problems like yours – although I personally prefer to avoid such designs whenever possible.

  • Related