简体   繁体   中英

non-static inner class name as a type parameter

is there a way to use a non-static inner class name as a type parameter? something like that:

public class Foo {
    ...
    // non-static inner class
    public class Bar {
    ...
    }
}

and somewhere

public Baz<Bar> obj;

if class Bar had been static I could have written

public Baz<Foo.Bar> obj;

but in this case a non-static variable in Foo cannot be used in Bar. The problem is I need to use a non-static member of Foo in Bar.

The real situation in a Java Play framework based web app:

public class SignupController extends Controller { 

    @Inject
    private UserService userService;
    ...
    public class SignupForm {

        public String validate() {
            if (userService.findUserByEmail(email) != null) {
                return Messages.get("error.email.is.in.use");
            }
            return null;
        }
    }
}

in a veiw template

@(signupForm: Form[controllers.SignupController.SignupForm])
...

userService must be seen in the inner class SignupForm and must not be static. This is why SignupForm cannot be static either.

unfortunately this will not be compiled.

is it possible to use SignupForm as a type parameter of class Form?

thanks in advance.

public Baz<Foo.Bar> obj;

To access the inner class as above, you don't need to make it static. It is directly accessible and perfectly compiles.

Why this works: Qualified Type Names

Because you are trying to access is a type using a type, which is perfectly legal for java compiler.

Here is a sample code. which compiles perfectly:

public class outer {    
  public class inner {    
  }
}

class another {
  private List<outer.inner> list = new ArrayList<>();    
  public List<outer.inner> method() {
    return new ArrayList<>();
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM