开发者

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 per开发者_Go百科form this?


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.


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.
}


http://en.wikipedia.org/wiki/Generics_in_Java


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

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜