跳至主要内容

Java Nested Class Implementation

Before we started, we have to review the definition of nested class:

Nested classes are divided into two categories: static and non-static. Nested classes that are declared static are called static nested classes. Non-static nested classes are called inner classes.

Features

Nested class is very common in Java code, and provides some benefits as oracle document says:

It is a way of logically grouping classes that are only used in one place;
It increases encapsulation;
It can lead to more readable and maintainable code.

And here, we are going to focus on the features and convenience that nested class bring to us. The following listed items are some of them:

  • They can access each other’s private members directly
  • Inner class can access outer class’s field directly

Secret of Access Private Member

Now, we move to a simple example of static nested class to see how Java make it. As the comment in the code pointed out, nested class and outer class reference each other’s private field/method directly:

public class OuterClass {
    private static int b = 1;

    public OuterClass() {
        // access the NestedClass's private field
        System.out.println(NestedClass.na);
        NestedClass.f(b);
    }

    private static class NestedClass{
        private static int na;
        {
            //access the OuterClass's private field
            System.out.println(b);
        }
        private static void f(int a) {
        }
    }

    public static void main(String[] args) {
        //access the NestedClass's private method
        new NestedClass();
    }
}

When we compile the upper code, we will see three classes (Why three? One more class is the synthetic class for constructor to use). This actually means nested class and outer class is actually two totally separated classes in the perspective of VM. So they can’t actually access the private member of each other like all other classes.

Not making it in the runtime environment (i.e. in the VM), Java choose to make it by the help of compiler.
The following is the byte code of NestedClass:

$ javap -c -p OuterClass\$NestedClass.class 
Compiled from "OuterClass.java"
class OuterClass$NestedClass {
  private static int na;

  private OuterClass$NestedClass();
    Code:
       0: aload_0
       ...

  static int access$000();
    Code:
       0: getstatic     #2                  // Field na:I
       3: ireturn

  static void access$100(int);
    Code:
       0: iload_0
       1: invokestatic  #2                  // Method f:(I)V
       4: return

  OuterClass$NestedClass(OuterClass$1);
    Code:
       0: aload_0
       1: invokespecial #1                  // Method "<init>":()V
       4: return
}

We can see from the byte code: In order to make na accessible, compiler add accessor with default visibility (access$000();). In this way, compiler make private field accessible. In the similar way, it can invoke private method through a proxy method with default visibility (access$100(int) vs f(int)).

To invoke private constructor is a little bit complex, because the name of constructor has to be the same, compiler add a fake parameter to make this method unique.

private OuterClass$NestedClass();

OuterClass$NestedClass(OuterClass$1);

Access Outer’s Field Directly

We are always told that we have to have an instance of outer class before we trying to instantiate a inner class (non-static nested class). This is because inner class needs a reference of outer class, and by this reference, inner class can refer to outer class’s field as if those fields are in the nested class.

public class OuterClass {
    private int a = 1;

    private class InnerClass {
        InnerClass() {
            System.out.println(a);
        }
    }
}    
class reflect.OuterClass$InnerClass {
  final reflect.OuterClass this$0; // <---- here

  reflect.OuterClass$InnerClass(reflect.OuterClass);
    Code:
       0: aload_0
       1: aload_1
       2: putfield      #1                  // Field this$0:Lreflect/OuterClass;
       5: aload_0
       6: invokespecial #2                  // Method java/lang/Object."<init>":()V
       9: getstatic     #3                  // Field java/lang/System.out:Ljava/io/PrintStream;
      12: aload_1
      13: invokestatic  #4                  // Method reflect/OuterClass.access$200:(Lreflect/OuterClass;)I
      ...
}

Conclusion

All in all, Java implement those features not in VM, not to provide special access right for those classes, but to add some synthetic method with higher visibility to overcome the problem. Details are listed as following:

  • Access private member – synthetic default accessor
  • Inner class access outer class’s field directly – synthetic reference of outer class

Written with StackEdit.

评论

此博客中的热门博文

Spring Boot: Customize Environment

Spring Boot: Customize Environment Environment variable is a very commonly used feature in daily programming: used in init script used in startup configuration used by logging etc In Spring Boot, all environment variables are a part of properties in Spring context and managed by Environment abstraction. Because Spring Boot can handle the parse of configuration files, when we want to implement a project which uses yml file as a separate config file, we choose the Spring Boot. The following is the problems we met when we implementing the parse of yml file and it is recorded for future reader. Bind to Class Property values can be injected directly into your beans using the @Value annotation, accessed via Spring’s Environment abstraction or bound to structured objects via @ConfigurationProperties. As the document says, there exists three ways to access properties in *.properties or *.yml : @Value : access single value Environment : can access multi...

Elasticsearch: Join and SubQuery

Elasticsearch: Join and SubQuery Tony was bothered by the recent change of search engine requirement: they want the functionality of SQL-like join in Elasticsearch! “They are crazy! How can they think like that. Didn’t they understand that Elasticsearch is kind-of NoSQL 1 in which every index should be independent and self-contained? In this way, every index can work independently and scale as they like without considering other indexes, so the performance can boost. Following this design principle, Elasticsearch has little related supports.” Tony thought, after listening their requirements. Leader notice tony’s unwillingness and said, “Maybe it is hard to do, but the requirement is reasonable. We need to search person by his friends, didn’t we? What’s more, the harder to implement, the more you can learn from it, right?” Tony thought leader’s word does make sense so he set out to do the related implementations Application-Side Join “The first implementation ...

Learn Spring Expression Language

When reading the source code of some Spring based projects, we can see some code like following: @Value( "${env}" ) private int value ; and like following: @Autowired public void configure (MovieFinder movieFinder, @ Value ("#{ systemProperties[ 'user.region' ] } ") String defaultLocale) { this.movieFinder = movieFinder; this.defaultLocale = defaultLocale; } In this way, we can inject values from different sources very conveniently, and this is the features of Spring EL. What is Spring EL? How to use this handy feature to assist our developments? Today, we are going to learn some basics of Spring EL. Features The full name of Spring EL is Spring Expression Language, which exists in form of Java string and evaluated by Spring. It supports many syntax, from simple property access to complex safe navigation – method invocation when object is not null. And the following is the feature list from Spring EL document : ...