Home > front end >  How to create child class with parant reference with java reflection and without switch
How to create child class with parant reference with java reflection and without switch

Time:12-16

I have a class A which is parant of classes AB, AC, AD. Also class A have enum field "type" which can be "A" \ "AB" \ "AC" \ "AD". So, how can i replace this switch with java reflections?

       public A f(Type type){
           A a;
           switch (type){
                    case A:
                        a = new A();
                        break;
                    case AB:
                        a = new AB();
                        break;
                    case AC:
                        a = new AC();
                        break;
                    case AD:
                        a = new AD();
                        break;
            }
        }
    ```

CodePudding user response:

Apperently, your switch statement is supposed to create a new object of the given type (of aa). To support this, you don’t need Reflection at all. You could use, e.g.

public class A {
  public final Supplier<A> factory;

  protected A(Supplier<A> factory) {
    this.factory = Objects.requireNonNull(factory);
  }

  public A() {
    this(A::new);
  }
}
public class AB extends A {
  public AB() {
    super(AB::new);
  }
}
public class AC extends A {
  public AC() {
    super(AC::new);
  }
}
public class AD extends A {
  public AD() {
    super(AD::new);
  }
}

Then, you can easily create a new object like

A aa = new AB();
A a = aa.factory.get();

// verify our assumption
if(a.getClass() != aa.getClass())
    throw new AssertionError();

For completeness, you can use Reflection, like

A a = aa.getClass().getConstructor().newInstance();

but the compiler will force you to deal with several potential exceptions, as there’s a lot that can go wrong at runtime, which can’t be checked at compile-time.

  • Related