InstantationException in newInstance of an anonymous class created

Update : this is more or less a hoax , and it turns out that this is the magic of the compiler, adding a constructor to pass to a local variable in build2.

For such an interface:

public interface IFoo { public int get(); }

The code below prints 1, 1, 2 and then throws an exception when trying to call getClass (). newInstance () for the value returned by build2, but does not call it when the value of build1 is returned. Any ideas why?

public class Foo {

 public static IFoo build1() {
  return new IFoo() { public int get() { return 1; } };
 }

 public static IFoo build2(final int v) {
  return new IFoo() { public int get() {return v;} };
 }

 public static void main(String[] args) throws Exception {
  IFoo foo, bar;

  foo = build1();
  System.out.println(foo.get());

  bar = foo.getClass().newInstance();  
  System.out.println(bar.get());

  foo = build2(2);
  System.out.println(foo.get());

  bar = foo.getClass().newInstance();  
  System.out.println(bar.get());
 }
}

My debugger indicates that in a call to newInstance (), getConstructor0 throws a NoSuchMethodException.

+3
source share
1 answer

Here's what happens:

  • newInstance()
  • , final, ,
  • , IFoo, build2,

, , :

import java.lang.reflect.*;
public class Foo {
    interface IFoo { public int get(); }

    public static IFoo build2(final int v) {
        return new IFoo() { public int get() {return v;} };
    }
    public static void main(String[] args) throws Exception {
        Class<?> klazz = build2(42).getClass();
        for (Constructor<?> c : klazz.getDeclaredConstructors()) {
            System.out.println(c);
        }
        // prints: Foo$1(int)
    }
}

, Foo$1 ( IFoo) int. return v, , , , .

Foo$1 (, , javap -c), , -. , , , final .

+4

Source: https://habr.com/ru/post/1758996/


All Articles