简体   繁体   中英

Method accepting two different types as parameter

I am writing a method that should accept as its parameter an object of one of two types which do not share a parent type other than Object. For example, the types are Dreams and Garlic. You can do both dreams.crush() and garlic.crush() . I want to have a method utterlyDestroy(parameter) , that would accept as its parameter both Dreams and Garlic.

utterlyDestroy(parameter) {
    parameter.crush()
}

Both Garlic and dreams are a part of some library, so having them implement an interface ICrushable (so that I could write utterlyDestroy(ICrushable parameter) ) is not an option.

My method body is quite long so overloading it would mean duplicating code. Ugly. I am sure I could use reflection and do some class hacking. Ugly.

I tried using generics but apparently I cannot write something like

utterlyDestroy(<T instanceof Dreams || T instanceof Garlic> parameter)

Is it possible to typecast Garlic to Dreams?

utterlyDestroy(Object parameter) {
    ((Dreams)parameter).crush()
}

This would still be ugly though. What are my other options and what is the preferred method of dealing with the situation?

How about this:

interface ICrushable {
    void crush();
}

utterlyDestroy(ICrushable parameter) {
    // Very long crushing process goes here
    parameter.crush()
}

utterlyDestroy(Dreams parameter) {
    utterlyDestroy(new ICrushable() { crush() {parameter.crush();});
}

utterlyDestroy(Garlic parameter) {
    utterlyDestroy(new ICrushable() { crush() {parameter.crush();});
}

New development should implement the ICrushable interface, but for the existing Classes, the parameter is wrapped in an ICrushable and passed to the utterlyDestroy(ICrushable) that does all the work.

How about something as simple as this?

utterlyDestroy(Object parameter) {    
    if(parameter instanceOf Dreams){  
        Dream dream = (Dreams)parameter;  
        dream.crush();
        //Here you can use a Dream 
    }  
    else if(parameter instanceOf Garlic){  
       Garlic garlic = (Garlic)parameter;   
        //Here you can use a Garlic  
       garlic.crush();  
   }
} 

If the utterlyDestroy is too complex and big and you just want to call the crush then this does what you want

You can implement a Haskell-esque Either-class in Java; something like this:

class Either<L,R>
{
    private Object value;

    public static enum Side {LEFT, RIGHT}

    public Either(L left)  {value = left;}
    public Either(R right) {value = right;}

    public Side getSide() {return value instanceof L ? Side.LEFT : Side.RIGHT;}

    // Both return null if the correct side isn't contained.
    public L getLeft() {return value instanceof L ? (L) value : null;}
    public R getRight() {return value instanceof R ? (R) value : null;}
}

Then you let that method take something of type Either<Dreams, Garlic> .

Simply use method overloading.

public void utterlyDestroy(Dreams parameter) {
    parameter.crush();
}

public void utterlyDestroy(Garlic parameter) {
    parameter.crush();
}

If you want to support more than these two types in the same way, you can define a common interface for them all and use generics.

You could use an interface and adapt your types to it.

Interface:

public interface Crushable {
  public void crush();
}

Example invocation:

public class Crusher {
  public static void crush(Crushable crushable) {
    crushable.crush();
  }
}

Example adapter factory method:

public final class Dreams {
  public static Crushable asCrushable(final Dream dream) {
    class DreamCrusher implements Crushable {
      @Override
      public void crush() {
        dream.crush();
      }
    }
    return new DreamCrusher();
  }

  private Dreams() {}
}

The consumer code looks like this:

  Dream dream = new Dream();
  Crushable crushable = Dreams.asCrushable(dream);
  Crusher.crush(crushable);

If you have many types to adapt, you could consider reflection. Here is an (unoptimized) adapter factory that uses the Proxy type:

public final class Crushables {
  private static final Class<?>[] INTERFACES = { Crushable.class };

  public static Crushable adapt(final Object crushable) {
    class Handler implements InvocationHandler {
      @Override
      public Object invoke(Object proxy, Method method, Object[] args)
          throws Throwable {
        return crushable.getClass()
            .getMethod(method.getName(), method.getParameterTypes())
            .invoke(crushable, args);
      }
    }

    ClassLoader loader = Thread.currentThread()
        .getContextClassLoader();
    return (Crushable) Proxy.newProxyInstance(loader, INTERFACES, new Handler());
  }

  private Crushables() {}
}

To the API consumer, this isn't that ugly:

  Dream dream = new Dream();
  Crushable crushable = Crushables.adapt(dream);
  Crusher.crush(crushable);

However, as is usual with reflection, you sacrifice compile-time type checking.

Creating an Interface Crushable seems like the cleanest way to go. Is subtyping Garlic or Dreams an option, and adding your Interface to the subtype?

Barring that, you can put common code in a private method, and have the two versions of utterlyDestroy do what they have to do to the individual objects before calling the common code. If you method body is long, probably need to break it up into private methods anyway. I'm guessing you already thought of this, though, as it is even more obvious a solution than adding an Interface.

You can bring the parameter in as an Object and then cast it. Is this what you mean by reflection? ie,

public void utterlyCrush(Object crushable) {
    if (crushable instanceOf Dream) {
         ...
    }
    if (curshable instanceOf Garlic) {
         ...
    }

But casting from Garlic to Dream is not an option given that one is not a subtype of the other.

如果您打算在项目的许多地方以相同的方式对待它们,我建议将它们包装在类中,比如适配器。

As I'm using :

void fooFunction(Object o){
Type1 foo=null;
if(o instanceof Type1) foo=(Type1)o;
if(o instanceof Type2) foo=((Type2)o).toType1();
// code
}

But that only works if Type2 can be converted to Type1

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