int
,long
,float
,double
),再次,第三次,再次 和 再次,我真的很接近崩溃。
这个问题以各种形式在StackOverflow上被提出:
共识似乎收敛为两种可能的选择:
- 使用某种代码生成器。
- 你能做什么呢?C'est la vie!
好的,第二个解决方案是我现在正在做的事情,但它正在逐渐危及我的理智,就像众所周知的酷刑技术一样。
自那些问题被提出并且Java 7出现以来已经过去了两年。因此,我对更简单和/或更标准的解决方案充满希望。
Does Java 7 have any changes that might ease the strain in such cases? I could not find anything in the condensed change summaries, but perhaps there is some obscure new feature somewhere?
While source code generation is an alternative, I'd prefer a solution supported using the standard JDK feature set. Sure, using
cpp
or another code generator would work, but it adds more dependencies and requires changes to the build system.The only code generation system of sorts that seems to be supported by the JDK is via the annotations mechanism. I envision a processor that would expand source code like this:
@Primitives({ "int", "long", "float", "double" }) @PrimitiveVariable int max(@PrimitiveVariable int a, @PrimitiveVariable int b) { return (a > b)?a:b; }
The ideal output file would contain the four requested variations of this method, preferrably with associated Javadoc comments e.t.c. Is there somewhere an annotation processor to handle this case? If not, what would it take to build one?
Perhaps some other trick that has popped up recently?
编辑:
重要提示:除非有理由,否则我不会使用原始类型。即使现在,在某些应用程序中使用包装类型仍然会对性能和内存产生非常真实的影响。
编辑2:
以max()
为例可以使用所有数值包装类型中可用的compareTo()
方法。这有点棘手:
int sum(int a, int b) {
return a + b;
}
如何在不写六七次的情况下,支持所有数值装箱类型的此方法?