Is it possible to create an anonymous class when using reflection?

I would like to be able to implement a method at runtime that is called before the object starts the initializers. This will allow me to set the fields that are used during initialization.

Here is an example:

class A {
  public A() {
    initialize();
  }
  public void initialize() { }
}

class B extends A {
  public String message;
  {
    System.out.println(message);
  }
}

public class MainClass {
  public static void main(final String[] args) throws Exception {

    Class<A> aClass = (Class<A>)Class.forName(args[0]);
    // what next in order to something like this even though
    // I don't know what subclass of A was passed in as an
    // argument above 
    A a = aClass.newInstance()
    {
      public void initialize() {
        this.message = args[1];
      }
    };
  }
}

I will probably end up using aspects, but I would like to know if there is a clean Java way.

+3
source share
3 answers

You mean something like this, assuming it will be compiled (which is not):

@Override
A a = aClass.newInstance()
{
  public void initialize() {
        this.message = args[1];
      }
};
+1
source

It looks like you want Dynamic Proxies , which are available since Java 1.3.

: mockito, , , , . , , , , .

C: ? , . , . :

public class Initializer<A> {

  public (abstract) void initialize(A parent);
}

final String args[] = ...;
Initializer<A> initializer = new Initializer<A>() {
  public void initialize(A parent) {
      parent.setMessage(args);
  }
};

, ( ).

0

, , , , . .

... .

, , / BCEL . . Java.

- , . ( , , - .)

0

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


All Articles