Invalid constructor reference when using local class?

后端 未结 2 1202
小蘑菇
小蘑菇 2021-02-02 09:09

Given the following code:

package com.gmail.oksandum.test;

import java.util.ArrayList;
import java.util.List;

public class Test {

    public static void main(         


        
相关标签:
2条回答
  • 2021-02-02 10:01

    It looks like LocalFoo is treated somehow like a non-static class. That's why it claims no instance of Test is in scope.

    From the tutorial:

    Local classes are non-static because they have access to instance members of the enclosing block. Consequently, they cannot contain most kinds of static declarations.

    https://docs.oracle.com/javase/tutorial/java/javaOO/localclasses.html

    The method foo() or the class LocalFoo must be static for this to work. But a class inside a method can't be declared as static. So you'd have to move it out of the method if foo() should remain nonstatic (as an inner, static class). Another option is to just use this:
    ls.stream().map(s -> new LocalFoo(s));

    There should be a way to just say Test.this.LocalFoo, but that doesn't work. And if it did the compiler should also just accept LocalFoo::new.

    There is a bug report now: https://bugs.openjdk.java.net/browse/JDK-8144673
    (See comment by Brian Goetz)

    0 讨论(0)
  • 2021-02-02 10:04

    One problem is that you are trying to instantiate the Arraylist by specifying the generic type in the list, but not using the same type in the Arraylist.

    Use : List ls = new ArrayList();

    Also please provide a default constructor for LocalFoo

    0 讨论(0)
提交回复
热议问题