Java: Extending Class At Runtime

前端 未结 4 823
北恋
北恋 2020-12-29 10:55

I have the capability to extend a class at compile time, but I need to be able to create an instance of this subclass at runtime using an instance of the superclass that was

4条回答
  •  独厮守ぢ
    2020-12-29 11:20

    I don't know if it's a sollution but if you have

    public static Foo foo = new Foo();
    

    and you want to replace it with Bar which extends Foo make Bar an Wrapper for of Foo and use reflection to let foo point to your Bar instance.

    public class Foo extends Bar {
      private bar; 
      public Foo(Bar oldInstance) {
         this.bar = oldInstance;
      }
    }
    

    and

    // exception handling ommitted
    public static void onStartup() {
       Class fooRefClass = FooRef.class;
       Field fooRef = fooRefClass.getDeclaredField("foo");
    
       Foo foo = (Foo)fooRef.get(null);
       Bar bar = new Bar(foo);
       fooRef.set(null, bar);
    

    }

    As told I don't know if this is possible in your case.

提交回复
热议问题