New features of jdk10: VaR and anonymous classes

brief introduction

I believe everyone has used anonymous classes. After learning the lambda expression in jdk8, you can find that some anonymous classes can be replaced by lambda expressions. The classes that can be replaced are called functional interfaces.

For a specific introduction to lambda expressions and anonymous classes, you can refer to the articles I wrote before. Not much here.

This paper mainly introduces some problems between VaR and anonymous classes.

Custom variables in anonymous classes

Let's look at a frequently used runnable anonymous class:

Runnable runnable = new Runnable() {
String className=Thread.currentThread().getName();
@Override
public void run() {
    log.info("inside runnable");
    }
};

Unlike the usual runable, we added a variable called classname to the anonymous class.

Because the runnable interface does not define how to access the newly created classname field, it uses runnable Classname will compile incorrectly.

But if we replace runnable with VaR:

var runnable = new Runnable() {
            String className=Thread.currentThread().getName();
            @Override
            public void run() {
                log.info("inside runnable");
            }
        };
        log.info(runnable.className);

You can see that something magical has happened, and the VaR variable can access the classname.

Anonymous classes in lambda expressions

We often use lambda expressions in the traversal and processing of streams, but few people may use anonymous classes in lambda expressions.

It doesn't matter. Let's take another example:

List<Object> objects=Stream.of(1,2,3,4).map(i-> new Object(){
            int count=i;
        }).filter(o -> o.count >0)
                .collect(Collectors.toList());
       log.info("{}",objects);

In the above example, we created a stream and returned the newly created anonymous object in the process of map. Inside the anonymous object, we defined a variable called count.

Note that in the following filter, we can actually directly use the object created in the map and directly access its newly defined count variable.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>