Alex Rivera | Logout

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

Asked 2011-02-24T03:24:25.873
9

I would like to be able to implement a method at runtime that is called before an object runs the initializers. This will allow me to set 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's 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 pure Java way.

Edit
Report

1 Answer

1

What you are trying to do would entail creating a new anonymous inner class that is a subclass of some class that you only know at runtime. Reflection cannot solve this problem.

Dynamic proxies might ... if you were trying to implement a dynamically loaded interface.

The only other approaches I can think of are to use BCEL or dynamic source code generation / compilation. And both are going to be very complicated. And neither count as pure Java.

My advice would be to take a fresh look at what it is you are trying to achieve. (Your question gives no hints as to what that might be, so it is hard to offer any practical suggestions.)

answered 2011-02-24T06:21:31.297

Your Answer