Skip to content

Instantly share code, notes, and snippets.

@vladris
Last active September 16, 2018 14:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vladris/843e20b4de148a4815686aec50547976 to your computer and use it in GitHub Desktop.
Save vladris/843e20b4de148a4815686aec50547976 to your computer and use it in GitHub Desktop.
Overloading methods with generic arguments
// Since generics in Java are removed at compile-time, we cannot overload methods
// based on generic types
// Below class does not compile:
// Erasure of method Foo(T1) is the same as another method in type Test<T1,T2>
// Erasure of method Foo(T2) is the same as another method in type Test<T1,T2>
class Generic<T1, T2> {
void Foo(T1 arg) {
}
void Foo(T2 arg) {
}
}
// Using dummy type guards, we can enable overloading
// Dummy types, just need to be different
class TypeGuard1 { }
class TypeGuard2 { }
// Compiles, guard argument doesn't have to be provided (unless T1 and T2 are
// the same)
class GenericWithGuards<T1, T2> {
void Foo(T1 arg, TypeGuard1...guard) {
}
void Foo(T2 arg, TypeGuard2...guard) {
}
static void Demo() {
GenericWithGuards<String, Integer> g = new GenericWithGuards<>();
// The right function gets called depending on argument type
g.Foo("Hello");
g.Foo(42);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment