Brandon
Brandon

Reputation: 109

How to make a typeless/generalized parameter in Java?

So say I have 2 methods: one adding two int's and the other adding two long's. Where the parameters are passed into the function.

How can I make 1 method that generalizes the parameter and return value to perform this?

Upvotes: 2

Views: 5473

Answers (4)

StriplingWarrior
StriplingWarrior

Reputation: 156459

I saw a trick like this in GWT:

public static <T> T add(long a, long b)
{
    return (T)(Object)(a + b); 
}

Use it like this:

long answer = add(1L, 2L);
int answer2 = add(1, 2);

While this does what you're asking for, the downside of this approach is that it opens you up to bad type casts. Even though you don't have to explicitly cast the value that is returned, you're still effectively telling the code to perform a cast to whatever the expected type is. You could accidentally say something like:

String t = add(1, 2);

Which would cause a runtime exception. Nevertheless, if you have a method whose return value will always be cast immediately after being returned, this trick can save consumers the hassle of explicitly casting the value.

Upvotes: 7

bcat
bcat

Reputation: 8941

Unfortunately, I don't think you can do this. First, Java generics can't be parameterized over primitives, so you'd have to use Integer and Long instead of int and long. Second, while you could have a method with generic type parameter T extends Number, there's no way to add two arbitrary Number subclasses in a generic fashion. In other words, the following code will not work:

public static <T extends Number> T add(T a, T b) {
    return a + b; // Won't compile, as the addition is not legal Java code.
}

Upvotes: 3

irreputable
irreputable

Reputation: 45433

long f(long x, long y){ ... }

int x=1, y=2;
f(x,y);

Upvotes: 0

Related Questions