1

I'm working on a library which is based on another library Lib, which is based on an SDK.

I need to have my class MyClass extend a class from Lib LibClass, which in turn extends a class from SDK SdkClass. In the constructor of LibClass, it passes a value to SdkClass' constructor via super(someArg).

However, for my code to work, I need to pass a different argument to SdkClass while keeping the rest the same. I don't have access to the source code of Lib. Is it possible to do it with some reflection?

Thank you!

tomzhi
  • 199
  • 2
  • 6
  • 2
    An [XY problem](https://en.wikipedia.org/wiki/XY_problem)? I suggest that you will want to describe why you think you need this? – Ole V.V. Jun 04 '23 at 03:30
  • Maybe you could do it by using bytecode engineering to *inject* a new constructor into the parent class. But that's modifying the class. AFAIK there's no way to do it without modifying the parent class. – Stephen C Jun 04 '23 at 04:05
  • @StephenC Thanks for the suggestion. There is a method in `Unsafe` to allocate the object without calling the constructor. But I don't know how to invoke constructors later with the desired argument. Not sure if it's even possible. – tomzhi Jun 04 '23 at 06:12
  • 1
    It isn't possible. – Stephen C Jun 04 '23 at 06:33

1 Answers1

1

While you ask a great question, unfortunately, what you want is not possible with reflection and plain-old Java in general. It breaks encapsulation, the same reason super.super.method() is not permitted in Java. The design you describe is clearly something like:

// SdkClass
public class Shape {
  public Shape(boolean isRectangle) {}
}

// LibClass
public class Rectangle extends Shape {
  public Rectangle() {
    super(true);
  }
}

// MyClass
public class Square extends Rectangle {
  public Square() {
    super();
  }
}

The point is that Rectangle is designed to be a base class for all rectangular shapes.

Although, if your application is containerized through some framework such as Spring, you could potentially leverage AOP to accomplish this: https://docs.spring.io/spring-framework/docs/3.2.x/spring-framework-reference/html/aop.html.

Oliver
  • 1,465
  • 4
  • 17