How does one handle a java method which returns a non-public sub-type via reflection?
Peter Levart
peter.levart at gmail.com
Tue Jan 16 10:05:39 UTC 2018
On 01/15/2018 11:02 PM, David Holmes wrote:
> I recall a very similar discussion in the past. You have to start with
> (public) statically known types, not with the dynamic type of the
> instances involved. In essence you have to reflectively emulate the
> method resolution process that occurs with a direct call and which
> uses static type information.
>
> David
> -----
Exactly, and in the example given by Jeffrey:
javafx.scene.control.Button button1 = ...;
javafx.scene.layout.VBox vbox = ...;
vbox.getChildren().add(button1);
The right translation of the last line to reflective invocations would
be this (skipping exception handling):
Method getChildrenMethod =
javafx.scene.layout.VBox.class.getMethod("getChildren");
Object children = getChildrenMethod.invoke(vbox);
Method addMethod = getChildrenMethod.getReturnType().getMethod("add",
javafx.scene.control.Button.class);
addMethod.invoke(children, button1);
You see, the compiler (javac) uses static type information (of the
locals for example) to locate the correct method. In case of method
chaining, it uses the declared return type of the previous method, etc...
Regards, Peter
More information about the jigsaw-dev
mailing list