简体   繁体   中英

How cast a subclass dynamically

Scenario: I have 2 different type of class: Fus and Eth . Both of them extend an abstract class called Abs .

Depending on some other info I have to cast Abs into Fus or Eth .

I have something like

while((rec == queue.poll()) != null) {
     insertInto(--rec-- Something here);
}

where queue is a ArrayDeque<Abs> , and rec is type of Abs . What I'd like to achieve is to cast rec in method insertInto because I have implemented 2 method: one is insertInto(Fus rec) and the other insertInto(Eth rec) .

I want to cast rec .

Something like

Class typeOf;
if (cond1)
    typeOf = Eth.class;
else
    typeOf = Fus.class;

In this way, in the insertInto(--rec--) I could cast that rec with typeOf

EDIT . Going to try to explain me a little better.

What I want to achieve is: I already know, before the while , which kind of subclass I want to cast rec that means I want to cast directly rec in the right subclass. Something like:

insertInto((typeOf) rec)

so I can use overloading of method insertInto. But of course this can't work, because typeOf is a Class object

EDIT2 Some other code hope it could explain what I'm trying to achieve:

Class typeOf;
if (condA) {
    typeOf = Fus.class;
} else {
    typeOf = Eth.class;
}

while ((rec = queue.poll()) != null) {
    insertInto((typeOf) rec); //Problem of course is here
}

You can do it using reflection.

Function<? extends Abs, ?> fn // Second one is your return type
if (cond1)
    fn = rec -> this.getClass().getDeclaredMethod("insertInto", Eth.class).invoke(rec);

fn(rec)

Although i will not advice it

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