javavisual-studio-codedebugging

vscode java debug - casting generic types watch expression


I am having problems while debuggin my app in vscode. I have an abstract class Container defined with generics in another class Element, and 3 subclasses of Container: Worker, Vehicle, Company. The subclasses them implement a method getID() that is defined in the subclasses but not in superclass. Is there a solution to evaluate subclasses method and its value while debugging?

example context code:

public class Element<E extends Container>{

private E Container;

public E getContainer(){
  return Container;
 }
}

public abstract class Container{

}

public class Worker extends Container{
 private ID;
 public getID(return ID);
}

I already tried to cast it to

(Worker)this.getContainer().getID();

but still not working.


Solution

  • Make sure you’re casting the container first, and then calling getID().

    ((Worker) this.getContainer()).getID();

    Or add an abstract method, so you would not need to cast it at all.

    public abstract class Container {
        public abstract Object getID();
    }