-1

I have a library that I am using in a project. It has a class which can be instantiated as

A object = new A(new B(value), C::new, D::new);

None of the classes A, B, C, D are public, although the constructors are.

So, I want to use Reflection to achieve this. But, I can't figure out how to do method reference C::new, D::new using reflection.

Would appreciate any pointers on how I can do this.

Eugene
  • 117,005
  • 15
  • 201
  • 306
Ashok Bommisetti
  • 314
  • 1
  • 3
  • 15

1 Answers1

2

The fact that a constructor reference is used is not important. You just need to know the functional interface type into which it is converted, and then create an instance of that.

In the case of a default constructor, this would probably be Supplier<...>. You'd get something like this:

Class<C> cKlass = ...;
Constructor<C> cCons = cKlass.getDeclaredConstructor();

Supplier<C> cSupp = () -> { // similarly for class D
        try {
            return cCons.newInstance();
        } catch (Exception e) {
            throw new RuntimeException("Can not default construct " + cKlass, e);
        }
};

...

Class<A> aKlass = ...;
Constructor<A> aCons = aKlass.getDeclaredConstructor(B.class, Supplier.class, Supplier.class);
A a = aCons.newInstance(b, cSupp, dSupp);
Jorn Vernee
  • 31,735
  • 4
  • 76
  • 93