Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a Java equivalent to Javascript's with statement? [duplicate]


Is there a similar way to declare a with-statement in Java (as in Javascript), or are there structural reasons why this would not be possible?


For example, this Javascript:
with(obj)
{
  getHomeworkAverage();
  getTestAverage();
  getAttendance();
}

...is nice and easy. However, it would seem that method calls have to be chained to their object(s) every time in Java, with no such graceful shortcuts avaiable:

obj.getHomeworkAverage();
obj.getTestAverage();
obj.getAttendance();

This is very redundant, and especially irritating when there are many methods to call.


  • So, is there any similar way to declare a with-statement in Java?
  • And if this is not possible, what are the reasons that it is possible in Javascript as compared to not possible in Java?
like image 612
Ian Campbell Avatar asked Dec 13 '12 06:12

Ian Campbell


2 Answers

There is no direct equivalent of "with".

If the methods are instance methods, you can give the target object reference a short identifier for use in a block:

{
  Student s = student;
  s.getHomeworkAverage();
  s.getTestAverage();
  s.getAttendance();
}

If the methods are static, you can use "import static":

import static java.lang.Math.*;

public class Test {
  public static void main(String[] args) {
    System.out.println(sqrt(2));
  }
}
like image 151
Patricia Shanahan Avatar answered Nov 04 '22 00:11

Patricia Shanahan


No, there's no with statement or a similar construct in Java.

like image 45
Codo Avatar answered Nov 04 '22 01:11

Codo