Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Anonymous classes field accessing on Java 1.8 compatibility with older versions

On Java 1.8, you don't have to define a field as final to it be acessed from anonymous classes.

For example, on older versions:

public void foo(final int bar) {
  new Runnable() {
    public void run() {
      System.out.println(bar);
    }
  };
}

But, now, on Java 1.8, bar does not need to be final:

public void foo(int bar) {
  new Runnable() {
    public void run() {
      System.out.println(bar);
    }
  };
}

So, if I compile my project, and the only resource implemented on Java 1.8 I'm using is this (I'm not using any lambdas, new classes, etc), will my code be executable on computers with older Java versions? If not, why?

like image 330
JoaaoVerona Avatar asked Jun 17 '14 13:06

JoaaoVerona


People also ask

When can you use anonymous classes?

Anonymous classes enable you to make your code more concise. They enable you to declare and instantiate a class at the same time. They are like local classes except that they do not have a name. Use them if you need to use a local class only once.

How do you call an anonymous class in Java?

Object = new Example() { public void display() { System. out. println("Anonymous class overrides the method display()."); } }; Here, an object of the anonymous class is created dynamically when we need to override the display() method.

Which of the following is true for an anonymous class?

18) Which of the following is true about the anonymous inner class? Explanation: Anonymous inner classes are the same as the local classes except that they don't have any name. The main use of it is to override methods of classes or interfaces.


2 Answers

When compiling with -target 1.8, javac will emit class files with a version number of 52.0 which is not supported by previous JVMs. So even if that’s the only difference it prevents you from executing files compiled with -target 1.8.

And javac doesn’t support specifying -source 1.8 and -target 1.7 at the same time. It will produce the error message source release 1.8 requires target release 1.8.

But indeed, if using effectively final variables is the only Java 8 feature you are using, there is no byte code difference besides the version number. If you compile such code targeting 1.8 and patch the class files reducing the version number to 51.0 they will run on Java 7. It’s as simple as reducing the byte at index 7 by one.

The tricky part is to discipline yourself to not using other Java 8 features when using a Java 8 compiler if you want to create Java 7 compatible code…

like image 183
Holger Avatar answered Sep 29 '22 23:09

Holger


I think Java 8 changed the class file major version to be different than Java 7 so an older JVM probably won't be able to load the newer classes.

If you compile with a -target 1.7, I don't know if you can use effectively final

like image 32
dkatzel Avatar answered Sep 29 '22 23:09

dkatzel