Reputation: 13
I have two java objects: WorkflowVo
and TypeAWorkflowVo
. TypeAWorkflowVo
is a subclass of WorkflowVo
. WorkflowVo has fields - name, profitCenter.
TypeAWorkflowVo has fields schedule, entity.
I store TypeAWorkflowVo
in a list using
List<? extends WorkflowVo> lsWfItems = new ArrayList<TypeAWorkflowVo>();
Is it possible to access the fields of TypeAWorkflowVo
(schedule, entity) from lsWfItems
at runtime?
I can only see WorkflowVo
fields(name, profitcenter) at runtime. In other words, I only see WorkflowVo
objects in lsWfItems
. Please advise.
Upvotes: 1
Views: 443
Reputation: 131526
I store TypeAWorkflowVo in a list using
List<? extends WorkflowVo> lsWfItems = new ArrayList<TypeAWorkflowVo>();
It is not possible.
<? extends SomeThing>
doesn't allow to add anything in the Collection but null
.
You should rather declare this if you want to be able to add WorkflowVo
instances in the List
:
List<WorkflowVo> lsWfItems = new ArrayList<WorkflowVo>();
Is it possible to access the fields of TypeAWorkflowVo(schedule, entity) from lsWfItems at runtime?
As you declare List<? extends WorkflowVo> lsWfItems
, you should do a cast to TypeAWorkflowVo
to use specify methods of it.
For example :
for (WorkflowVo workFlow : lsWfItems){
if (workFlow instanceof TypeAWorkflowVo){
TypeAWorkflowVo typeWorkFlow = (TypeAWorkflowVo) workFlow;
...
}
}
Now, it you may avoid casting, it would be better.
Ideally, if you store only TypeAWorkflowVo
instances in your List
, declare rather :
List<TypeAWorkflowVo> lsWfItems = new ArrayList<TypeAWorkflowVo>();
Upvotes: 0
Reputation: 325
The way you have currently written it will not work. You do have a couple of options
Each of these have their merits and fails and the decision will entirely depend on the situation and the definition of that object. Should the fields be on the super class or not? Should that list be of the sub class, or the super class. What do you gain out of each of these methods in the app. All these would be answered from the app
Upvotes: 2