24

I wonder if it is possible to require that a java method parameter is of any type from finite set of types. For example - I am using a library where two (or more) types have common methods, but their lowest common ancestor in the type hierarchy is Object. What I mean here:

   public interface A {
      void myMethod();
   }

   public interface B {
      void myMethod();
   }
...
   public void useMyMethod(A a) {
      // code duplication
   }

   public void useMyMethod(B b) {
      // code duplication
   }

I want to avoid the code duplication. What I think of is something like this:

   public void useMyMethod(A|B obj){
      obj.myMethod();
   }

There is similar type of syntax in java already. For example:

  try{
     //fail
  } catch (IllegalArgumentException | IllegalStateException e){
     // use e safely here
  }

Obviously this is not possible. How can I achieve well designed code using such type of uneditable type hierarchy ?

4
  • 2
    As you have no common interface, how should your compiler check that the two or more classes have a common "interface"? The problem is also that the code you define as "duplication" is no duplicate according to the program code as you have two different class hierarchies - the code only looks the same but works on completely different data structures.
    – Smutje
    Commented Dec 16, 2014 at 11:15
  • This is easy in Scala, but that probably doesn't help you. All I can suggest is making a wrapper for one interface that implements the other (or wrappers for both that implement the same interface).
    – lmm
    Commented Dec 16, 2014 at 11:17
  • 4
    Since you've tagged it for “design patterns”, the adapter pattern comes to mind. But that requires you to code a wrapper for each of those types. Without doing that, I'm afraid that there will not be a statically type-safe solution to this. At least, I would be surprised if there were.
    – 5gon12eder
    Commented Dec 16, 2014 at 11:17
  • Hey @egelev, did you find any of the answers useful? If so please give the author some kudos and mark one as accepted! Thanks.
    – Yogster
    Commented Dec 18, 2014 at 11:43

8 Answers 8

17

What about passing the function as a parameter to your useMyMethod function?

If you are using Java < 8:

public interface A {
    void myMethod();
}

public interface B {
    void myMethod();
}

public void useMyMethod(Callable<Void> myMethod) {
    try {
        myMethod.call();
    } catch(Exception e) {
        // handle exception of callable interface
    }
}

//Use

public void test() {
    interfaceA a = new ClassImplementingA();
    useMyMethod(new Callable<Void>() {
        public call() {
            a.myMethod();
            return null;
        }
    });

    interfaceB b = new ClassImplementingB();
    useMyMethod(new Callable<Void>() {
        public call() {
            b.myMethod();
            return null;
        }
    });
}

For Java >= 8, you could use Lambda Expressions:

public interface IMyMethod {
    void myMethod();
}

public void useMyMethod(IMyMethod theMethod) {
    theMethod.myMethod();
}

//Use

public void test() {
    interfaceA a = new ClassImplementingA();
    useMyMethod(() -> a.myMethod());

    interfaceB b = new ClassImplementingB();
    useMyMethod(() -> b.myMethod());
}
2
  • 2
    Not bad but it forces us to expose to the caller what methods we will invoke on the argument. Changing the implementation (simply calling another method) might force us to go and edit each use of the function. And if we want to call more than one method, it quickly becomes tedious.
    – 5gon12eder
    Commented Dec 16, 2014 at 11:43
  • 2
    Hey @5gon12ender, your points are valid. Using an adapter has the benefit of encapsulating the call to the method, so if the method needs to be changed then only the adapter class has to be changed. On the other hand you would need to create an adapter per interface, which can become even more tedious than a functional solution. It really depends on the scope of the code (is it the internal code of a small class or a widely-used function?) and how likely to change the implementation is, I would say.
    – Yogster
    Commented Dec 16, 2014 at 11:54
13

Try using Adapter design pattern.

Or, if it's possible, add some base interface:

public interface Base {
    void myMethod();
}

public interface A extends Base {}
public interface B extends Base {}
...
public void useMyMethod(Base b) {
    b.myMethod()
}

Also, you can use something similar to this

5
  • 4
    You may have missed the part "How can I achieve well designed code using such type of uneditable type hierarchy ?"
    – Smutje
    Commented Dec 16, 2014 at 11:18
  • 3
    Doesn't work as shown because Base does not have the required method.
    – BarrySW19
    Commented Dec 16, 2014 at 11:20
  • I still cannot see the pattern. pbabcdefp 's answer makes it much clearer.
    – 5gon12eder
    Commented Dec 16, 2014 at 11:23
  • @5gon12eder, I think Adapter is well-known pattern and may be easily googled. Also I added a link to Wikipedia page. Commented Dec 16, 2014 at 11:43
  • I think Adapter + Delegate is the way to go, as in @pbespechnyi's answer. This way, no need to modify the existing type hierarchy. Commented Dec 16, 2014 at 18:39
8

You could write an interface MyInterface with a single method myMethod. Then, for each type you want to consider as part of the finite set, write a wrapper class, like this:

class Wrapper1 implements MyInterface {

    private final Type1 type1;

    Wrapper1(Type1 type1) {
        this.type1 = type1;
    }

    @Override
    public void myMethod() {
        type1.method1();
    }
}

Then you just need to use a MyInterface rather than one of the finite set of types, and the appropriate method from the appropriate type will always get called.

Note that to actually use these wrapper classes to call the method myMethod you would have to write

myMethod(new Wrapper1(type1));

This is going to get a bit ugly as you are going to have to remember the name of the wrapper class for each type in the set. For this reason, you may prefer to replace MyInterfacewith an abstract class with several static factories that produce the wrapper types. Like this:

abstract class MyWrapper {

    static MyWrapper of(Type1 type1) {
        return new Wrapper1(type1);
    }

    static MyWrapper of(Type2 type2) {
        return new Wrapper2(type2);
    }

    abstract void myMethod();
}

then you can call the method using the code

myMethod(MyWrapper.of(type1));

The advantage of this approach is that the code is the same no matter which type you use. If you use this approach you have to replace implements MyInterface in the Wrapper1 declaration with extends MyWrapper.

5
  • 1
    You may have missed the part "How can I achieve well designed code using such type of uneditable type hierarchy ?"
    – Smutje
    Commented Dec 16, 2014 at 11:18
  • @Smutje, you don't need to edit the (original) type hierarchy. That's why this is called a Wrapper. Commented Dec 16, 2014 at 16:11
  • 1
    You should probably add a second code snipped how this wrapper is actually used with the two objects methodCall(new Wrapper( t1 );) - I would even think about a single Wrapper-Class with two constructors, one for each interface
    – Falco
    Commented Dec 16, 2014 at 16:55
  • 1
    @Falco Excellent point. I've improved my answer following your advice, except i've gone for static factories rather than multiple constructors. Commented Dec 16, 2014 at 17:16
  • 1
    This is my favorite answer. That's just another way to implement the Adapter pattern mentioned in other answers, by using the Delegate pattern to implement the adapters themselves. It has quite a bit of overhead in terms of code though, since you need to define the new common interface and two delegating classes. So it's probably only worth it if you have a lot of duplicated code. Commented Dec 16, 2014 at 18:37
5

Well, the correct way to model your requirement would be to have myMethod() declared in a supertype interface C which both A and B extend; your method then accepts type C as its parameter. The fact that you have trouble doing this in the situation you describe indicates you are not modelling the class hierarchy in a way that actually reflects how they behave.

Of course, if you can't change the interface structure then you could always do it with reflections.

public static void useMyMethod(Object classAorB) throws Exception {
    classAorB.getClass().getMethod("myMethod").invoke(classAorB);
}
2
  • 3
    To make this statically type-safe at least at the caller's site, I'd consider making the method that accepts Object private and provide public methods overloaded for each type that is to be supported. These simply delegate to the method you show. This does require a little code duplication but only technical one-liners, none of the business logic.
    – 5gon12eder
    Commented Dec 16, 2014 at 11:26
  • @5gon12eder that's exactly the approach I would take - public methods that ensure type-safety and call the underlying private method!
    – Falco
    Commented Dec 16, 2014 at 16:50
3

This might not constitute a best practice, but could you make a new class (call it C), that contains the parts from A and B that are duplicated, and the make a new method that takes C, have your methods that take A and B make a C instance and call the new method?

So that you have

class C {
    // Stuff from both A and B
}

public void useMyMethod(A a) {
    // Make a C
    useMyMethod(c);
}

public void useMyMethod(B b) {
    // Make a C
    useMyMethod(c);
}

public void useMyMethod(C c) {
    // previously duplicated code
}

That would also let you keep any non duplicated code in the methods for A and B (if there is any).

3

This looks to me much like the template pattern:

public interface A {

    void myMethod();
}

public interface B {

    void myMethod();
}

public class C {

    private abstract class AorBCaller {

        abstract void myMethod();

    }

    public void useMyMethod(A a) {
        commonAndUseMyMethod(new AorBCaller() {

            @Override
            void myMethod() {
                a.myMethod();
            }
        });
    }

    public void useMyMethod(B b) {
        commonAndUseMyMethod(new AorBCaller() {

            @Override
            void myMethod() {
                b.myMethod();
            }
        });
    }

    private void commonAndUseMyMethod(AorBCaller aOrB) {
        // ... Loads of stuff.
        aOrB.myMethod();
        // ... Loads more stuff
    }
}

In Java 8 it is much more succinct:

public class C {

    // Expose an "A" form of the method.
    public void useMyMethod(A a) {
        commonAndUseMyMethod(() -> a.myMethod());
    }

    // And a "B" form.
    public void useMyMethod(B b) {
        commonAndUseMyMethod(() -> b.myMethod());
    }

    private void commonAndUseMyMethod(Runnable aOrB) {
        // ... Loads of stuff -- no longer duplicated.
        aOrB.run();
        // ... Loads more stuff
    }
}
2

A dynamic proxy can be used to create a bridge between a common interface you define and the objects implementing the other interfaces that conform to the new interface. Then, you can have your useMyMethods convert the parameter to the new interface (as a dynamic proxy) and have your common code written in terms only of the new interface.

This would be the new interface:

interface Common {
  void myMethod();
}

Then, with this invocation handler:

class ForwardInvocationHandler implements InvocationHandler {
  private final Object wrapped;
  public ForwardInvocationHandler(Object wrapped) {
    this.wrapped = wrapped;
  }
  @Override
  public Object invoke(Object proxy, Method method, Object[] args)
      throws Throwable {
    Method match = wrapped.getClass().getMethod(method.getName(), method.getParameterTypes());
    return match.invoke(wrapped, args);
  }
}

You can have your methods like this:

public void useMyMethod(A a) {
  useMyMethod(toCommon(a));
}

public void useMyMethod(B b) {
  useMyMethod(toCommon(b));
}

public void useMyMethod(Common common) {
  // ...
}

private Common toCommon(Object o) {
  return (Common)Proxy.newProxyInstance(
    Common.class.getClassLoader(), 
    new Class[] { Common.class }, 
    new ForwardInvocationHandler(o));   
}

Note that to simplify matters you could even elect one of your existing interfaces (A or B) to be used as the common interface.

(Look at another example here, and also at other ideas around this subject)

1

The correct way is to use Java Generics.

See http://docs.oracle.com/javase/tutorial/java/generics/bounded.html

5
  • How would you constrain the generic type parameter to a finite set of types?
    – dcastro
    Commented Dec 16, 2014 at 11:31
  • Well obviously you have a base interface or object type, say type "AorB", which has a method definition or implementation. So you define a public interface Functor<T extends AorB>{}. You can multiple bound T to a series of types: <T extends B1 & B2 & B3>
    – StarShine
    Commented Dec 16, 2014 at 11:35
  • 1
    The OP cannot edit the existing interfaces to make them extend a common interface - "How can I achieve well designed code using such type of uneditable type hierarchy?"
    – dcastro
    Commented Dec 16, 2014 at 11:36
  • Well, using multiple-bound extends, it is still possible.
    – StarShine
    Commented Dec 16, 2014 at 11:37
  • 2
    I don't use Java, but looking at the documentation, it seems you can force a generic type parameter to extend multiple types (T extends A & B) - but you can't force it to extend one of multiple types.
    – dcastro
    Commented Dec 16, 2014 at 11:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.