Lazy parameter type in Java?
i have a question about parameter passing in Java. Let's say i have a method:
public void x(Object o)
Let's say i call x(3) and x("abc"). x(3) will take a little bit mor开发者_StackOverflow社区e time because a new Integer is constructed, since 3 is not an Object. Assuming i can't change the method calls, only the method implementation (and parameter type), is there a way to prevent this Integer construction until some point in the method x where i know it's really needed?
Thanks, Teo
No, Java does not have a way to make it evaluate the arguments to a method lazily in the way you describe.
Section 15.12.4 of The Java Language Specification explains exactly how method invocation works and how the arguments to a method are evaluated before it is invoked.
You can create a lazily evaluated object like Callable
public void method(Callable<Object> callable) {
// if you really need it
Object obj = callable.call();
}
The reason you don't see this more often is that it is usually slower and more complicated.
BTW: x(3)
won't create an object because this is actually x(Integer.valueOf(3))
and valueOf
has a cache of small Integer values.
For most applications the cost of creating a very small, simple object like Integer is small compared with the complexity of creating a lazily evaluated value.
If you want to avoid object creation you could have
public void x(Object o) ;
public void x(int i);
or
public void x(long l);
or
public void x(double d);
The later example avoid creating lots of variations of x
.
1) There is no way to postpone the object creation
2) The difference will be that small that you don't need to care
If the method x is only dealing with integers not any other types of objects then you can change the method to
public void x(int x){
//do something and then create the object as needed.
}
But in your case the method is about to take any kind of object so there is no other way other than creating a new integer object.
精彩评论