What exactly happens in this piece of Java code?

Here is the code:

timer.schedule(new TimerTask() { public void run() { synchronized(this) { try { // System.out.println(" ITERATION = "); pachubeCLI.update(78164); } catch (PachubeException e) { // If an exception occurs it will print the error message from the // failed HTTP command System.err.println(e.errorMessage); } catch (IOException e) { System.err.println(e); } } } }, 0, 5*1000); 

I can say that the code is mainly used to schedule operations using an object of class Timer . The parameters passed to the schedule method according to eclipse are equal (TimerTask task,long delay, long period) . But, looking at this code, the entire block of code is passed as the first parameter instead of a reference to the TimerTask class. I have never seen such a method before. What exactly is going on here?

Some background: the schedule method of the Timer object is used to update the feed on Xively (formerly COSM (formerly pachube)).

Also I donโ€™t know which tag describes what is happening here. If you add it or write a comment.

+6
source share
3 answers

What you are looking at is called anonymous inner class.

See javadoc here: http://docs.oracle.com/javase/tutorial/java/javaOO/anonymousclasses.html

and this question: How are anonymous (internal) classes used in Java? .

And for the record, both the tags you used in your question are suitable.

+8
source

The schedule method here expects arguments of object of class type TimerTask and two other arguments , possibly int and time in ms . We pass the object to an anonymous inner class.

The code creates an instance of the TimerTask class, but we donโ€™t even give the class a name - an anonymous inner class .

Reference sheets for an anonymous class.

  • An anonymous class is declared and initialized at the same time.
  • An anonymous class must extend or implement only one class or only one class or interface and
  • Since the anonymous class does not have a name, it can be used only once.
+2
source

The logical equivalent of what is happening:

  • TimerTask class TimerTask , e. MyTimer extends TimerTask

  • Creating an instance of the new class MyTimer mt = new MyTimer()

  • Actual function call timer.schedule(mt, 0, 5*1000);

The concept is called an anonymous inner class . This is what happens in the first step. Step 2 and 3 can also be combined. Instances can be created directly where they are needed. This is called an anonymous object .

For a deeper understanding, you should read these concepts. They are not difficult to understand. They are often used if you need a standard interface instance (for example, an ActionListener in GUI programming).


For completeness, there is also the idiom of double-bracket initialization . But this is not a good practice in general.

+1
source

Source: https://habr.com/ru/post/953506/


All Articles