简体   繁体   中英

How to access subclass fields at runtime using superclass instance

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.

The way you have currently written it will not work. You do have a couple of options

  1. Check that each item is of type TypeAWorkflowVo, then cast to this class and retrieve the values
  2. Make the list with type argument of TypeAWorkflowVo
  3. Make the fields on TypeAWorkflowVo available to be accessed through generic abstract methods on WorkflowVo
  4. Move the fields to WorkflowVo

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

I store TypeAWorkflowVo in a list using

List<? extends WorkflowVo> lsWfItems  = new ArrayList<TypeAWorkflowVo>();

It is not possible.

<? extends SomeThing> <? 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 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>();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM