How to define a class and instantiate it as one construct

I would like to reduce the following lines of code. There is no need to declare a class and then instantiate to run it. It should be possible to write code so that you can define the class and instantiate it as one construct. I still need runOnUiThread to run it, but I'm looking for a concise way to combine class definition and instantiation. I saw how this is done somewhere, but I canโ€™t remember how it was done:

class OnRunnableCompleted implements Runnable { @Override public void run() { } } OnRunnableCompleted onRunnableCompleted = new OnRunnableCompleted(); runOnUiThread(onRunnableCompleted); 
+4
source share
4 answers
 runOnUiThread(new Runnable() { public void run() {} }); 

This creates an anonymous class that implements the Runnable interface and overrides the abstract run() method to be non-op.

The general form of an anonymous class

 new Name(superCtorParam0, superCtorParam1) { member0; member1; } 

Where

  • Name is the name of the interface or class to extend / implement,
  • superCtorParam 0 ... n are Name constructor parameters
  • member 0 ... n are fields, methods, initializers, inner classes of an anonymous class, as in any other class declaration
+12
source

What about...

 Runnable calculatePI = new Runnable(){ public void run(){/*calculate pi*/} } //Any time you need to calculate pi runOnUiThread(calculatePI); 

This reduces code and prevents the re-creation of anonymous classes. In my Android development, I often use this solution. It works well.

+2
source

In JDK 8, you can do something like this:

 yourMethod(() -> System.out.println("RUN!")); 
0
source

Use the anonymus class as

 runOnUiThread(new Runnable() { public void run() {} }); 
0
source

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


All Articles