oop - Java - Extracting code to a generic method when method names are different -


i have code iterates on objects of type mytype:

// result of type map<long, mytype> (final map.entry<long, mytype> somemytypeobject: result.entryset() {    // bunch of stuff     status status = somemytypeobject.getstatus();     // more stuff } 

no i'm adding flow handles result of type map<long, mynewtype> needs exactly same thing while difference method returns status named differently (let's - getobjectstatus() instead of getstatus()). can't change either method's name.

i wanted this:

public <t> doiterationwork(map<long, t> result) {    // bunch of stuff     status status = somemytypeobject.getstatus();     // more stuff } 

the problem - can't use method because can't tell type t. thought overloading 3 methods:

public void getstatus(mytype obj) { return obj.getstatus(); }  public void getstatus(mynewtype obj) { return obj.getobjectstatus(); }  public void getstatus(object obj) { // throw exception } 

but can't because call set according static type , not dynamic type (thus object overload).

is there pattern handle such case without changing original classes not option right now?

it's not elegant, check type instanceof, cast object , call corresponding method.

something this:

status status;  if (somemytypeobject instanceof mytype) { // it's mytype object      mytype mytypeobject = (mytype) somemytypeobject;     status = mytypeobject.getstatus();  } else { // it's mynewtype object      mynewtype mynewtypeobject = (mynewtype) somemytypeobject;     status = mynewtypeobject.getobjectstatus();  } 

Comments

Popular posts from this blog

Android layout hidden on keyboard show -

google app engine - 403 Forbidden POST - Flask WTForms -

c - Why would PK11_GenerateRandom() return an error -8023? -