Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing an argument that could be of multiple types to a method in Java?

I am using a library with a method foo with a signature like this:

TypeR foo(TypeA first, int second)
TypeR foo(TypeB first, int second)
TypeR foo(TypeC first, int second)

I am writing my own method bar calling foo, and I want to directly pass the first parameter along to foo:

bar(??? first, int baz) {
    int second = someCalculation(baz);
    return foo(first, second);
}

My problem is that I do not know what type I should give to the parameter first in bar. There does not seem to be union typs in Java. How can I solve this without having to write three almost identical versions of bar?

The types TypeA to TypeC do not share a common interface, and I have no control over them or foo since they are in an external library. All I can control is how I implement bar.

like image 625
Anders Avatar asked Sep 16 '25 17:09

Anders


1 Answers

The closest I can think of is something like this (removing the stuff relating to second since it is irrelevant to the point).

TypeR bar(Object first) {
  TypeR retvalue;
  if (first instanceof TypeA)
    retvalue = foo( (TypeA)first );
  else if (first instanceof TypeB)
    retvalue = foo( (TypeB)first );
  else if (first instanceof TypeC)
    retvalue = foo( (TypeC)first );
  return retvalue;
}

If there is a more specific known supertype of TypeA etc., you could obviously use that instead of Object as the parameter.

This is only possible if all three versions of foo have the same return type.

Sadly, this "solution" is not really better, and maybe worse, than writing three overloaded versions of bar.

like image 144
Dave Costa Avatar answered Sep 19 '25 07:09

Dave Costa